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