简体   繁体   中英

In Yii2 i has passing model value but its showing as a null

There is my controller code

 if ($this->request->isPost) {
            $model->created_by = Yii::$app->user->identity->id;
            $model->created_at = date('Y/m/d');
            // echo $model->created_at;die;
            if ($model->load($this->request->post()) && $model->save()) {
                return $this->redirect(['index', 'id' => $model->id]);
            }
        } 

and there is my model rule

public function rules()
{
    return [
        [['deduction_type'], 'required'],
        [['created_at'], 'safe'],
        [['created_by'], 'integer'],
        [['deduction_type'], 'string', 'max' => 100],
    ];
}

My problem is a every time i pass the value in create_at and create_by that is save in databasde as a null in want my value in db

Instead of your way

 if ($this->request->isPost) {
            //Move that two Lines inside the if
            $model->created_by = Yii::$app->user->identity->id;
            $model->created_at = date('Y/m/d');

            // echo $model->created_at;die;
            if ($model->load($this->request->post()) && $model->save()) {
                return $this->redirect(['index', 'id' => $model->id]);
            }
        }

I usually do the following:

 if ($this->request->isPost) {
            if ($model->load($this->request->post()) && $model->validate()) {
                $model->created_by = Yii::$app->user->identity->id;
                $model->created_at = date('Y/m/d');
                $model->save();
                return $this->redirect(['index', 'id' => $model->id]);
            }
        }

validate() ->Checks if the Inputs are Correct according to your rules. Afterwards you know that the entries were correct and you can set your values.
This is my usual way of tackling this problem. You can also wrap $model->save(); with an if to check your changes as well and to catch the potential false of save().

Check your POST, is it send empty filds created_at and created_by? don't send this fields in post and load() method will not replace it on null values.

If you are really want to insert current user id and current time, use the BlameableBehavior and TimestampBehavior.

BlameableBehavior automatically fills the specified attributes with the current user ID. https://www.yiiframework.com/doc/api/2.0/yii-behaviors-blameablebehavior

TimestampBehavior automatically fills the specified attributes with the current timestamp. https://www.yiiframework.com/doc/api/2.0/yii-behaviors-timestampbehavior

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