首页 > 解决方案 > Yii2 控制器发布请求为 NULL

问题描述

谁能说出为什么数据库中的控制器帖子为 NULL ?但在 vardump 中有数据

控制器

 $model = new Reg();

 $model->load(\Yii::$app->request->post());
 $model->save();   

模型

public function rules()
{
    return [
        [['title', 'article', 'fio','country', 'position','tel', 'email','cert'], 'required',  'message'=>'required'],
        [['title', 'article', 'fio','country', 'position','tel', 'email','cert'], 'string'],
        [['title', 'article'], 'safe'],
    ];
}

看法

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?php echo $form->field($model,'title')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'article')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'fio')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'country')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'position')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'tel')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'email')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'cert')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php ActiveForm::end() ?>

标签: phpyii2

解决方案


当模型 validate() 返回 true 时,ActiveRecord 将数据插入数据库。如果模型属性验证发生此错误并且 validate() 方法返回错误的发布数据将不会插入到数据库以查看错误,您可以使用将控制器更改为此

 $model = new Reg();   

    if($model->load(Yii::$app->request->post()) && $model->validate() && $model->save()){   
        return $this->redirect(['index']);   
    }   

    return $this->render('create', ['model' => $model]);   
}  

您可以查看是否验证错误并修复此问题


推荐阅读