skip to Main Content

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, every time I pass the value in create_at and create_by data save in database as a null.
I want my actual value in db.

3

Answers


  1. 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 falseof save().

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
  3. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search