Answer the question
In order to leave comments, you need to log in
What is the correct way to set the default value in Yii2?
The situation when it is necessary to assign a default value in the model is very common, how can this be done in Yii2 there are many ways, but what is the right way ?? I have been studying Yii2 not so long ago, and this question arose from here. So, what was hard to find, using the example of user_id from the current session:
1) Register in the beforeValidation method
public function beforeValidation(){
if($this->isNewRecord()){
$this->user_id = Yii::$app->user->identity->id
}
}
public function beforeSave($insert){
if($insert){
$this->user_id = Yii::$app->user->identity->id
}
}
public function rules()
{
return [
['user_id', 'integer'],
['user_id', 'default', 'value' => Yii::$app->user->identity->id ],
];
}
public function behaviors()
{
return [
'blame' => [
'class' => BlameableBehavior::className(),
'attributes' => [
BaseActiveRecord::EVENT_BEFORE_INSERT => 'user_id'
],
]
];
}
$model = new SomeThing(['user_id' => Yii::$app->user->identity->id ]);
Answer the question
In order to leave comments, you need to log in
it is better to use option number 2. it more explicitly sets the default value, in addition, after applying the default validator, it is possible to check the given value using other validators.
The afterSave and beforeSave options will make the code less readable.
The option with behaviors - will give a
bunch of extra code and complicate its understanding
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question