S
S
Sergei Iamskoi2016-05-17 16:50:51
Yii
Sergei Iamskoi, 2016-05-17 16:50:51

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
}
}

1.5) or beforeSave
public function beforeSave($insert){
if($insert){
$this->user_id = Yii::$app->user->identity->id
}
}

2) In the model in the rules we write:
public function rules()
    {
        return [
            ['user_id', 'integer'],
            ['user_id', 'default', 'value' => Yii::$app->user->identity->id ],
        ];
    }

3) Using behaviors:
public function behaviors()
    {
        return [
            'blame' => [
                'class' => BlameableBehavior::className(),
                'attributes' => [
                    BaseActiveRecord::EVENT_BEFORE_INSERT => 'user_id'
                ],
            ]
        ];
    }

4) There is also an option with passing to the model when declaring an object
$model = new SomeThing(['user_id' => Yii::$app->user->identity->id ]);

So how is it more correct in the situation of specifying the current user by default?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2016-05-17
@syamskoy

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 question

Ask a Question

731 491 924 answers to any question