简体   繁体   中英

Yii2 Controller post request is NULL

Can anyone tell why controller post in database is NULL ? but in vardump have data

Controller

 $model = new Reg();

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

Model

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'],
    ];
}

View

<?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() ?>

ActiveRecord insert data to db when model validate() returned true. If this error occured for model attributes validating and validate() method returned false post data wil not insert to db for view error you can use change the controller to this

 $model = new Reg();   

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

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

and you can view errors in validate or not and fix this

$model->save(false);

will save your data forcefully by skipping validation but it is bad practice,

use $model->getErrors() after save, It will return list of validation errors which prevent data from storing from database

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM