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
Instead of your way
I usually do the following:
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 anif
to check your changes as well and to catch the potentialfalse
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