Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting default values on create and update in yii

Tags:

yii2

I am trying to update some fields in yii 1.1 using the following rules, but it is not working.

public function rules()
{
    return [
       ['CreatedOn','default','value'=>time(),'isEmpty'=>true,'on'=>'insert'],
       ['CreatedBy','default','value'=>\Yii::$app->user->identity->id,'isEmpty'=>true,'on'=>'insert'],
       ['ModifiedOn','default','value'=>time(),'isEmpty'=>true,'on'=>'update'],
       ['ModifiedBy','default','value'=>\Yii::$app->user->identity->id,'isEmpty'=>true,'on'=>'update'],
    ];
}

I am looking to update CreatedBy and CreatedOn when inserting, and ModifiedBy and ModifiedOn when updating.

like image 556
Nadeem Avatar asked Mar 10 '15 13:03

Nadeem


1 Answers

From soju's excellent answer, with Yii2:

By default, a model supports only a single scenario named default

You should therefore set the scenario manually in your controller i.e:

$model->scenario = 'insert';

You could also use when instead of on i.e:

['CreatedOn', 'default', 'value'=>time(), 'isEmpty'=>true, 'when'=>
    function($model) { return $model->isNewRecord; }
],
['ModifiedOn', 'default', 'value'=>time(), 'isEmpty'=>true, 'when'=>
    function($model) { return !$model->isNewRecord; }
],

An alternative to setting them in rules() would be to use beforeSave() to set them:

public function beforeSave($insert) {
    if ($insert) {
        $this->CreatedBy = \Yii::$app->user->identity->id;
        $this->CreatedOn = time();
    } else {
        $this->ModifiedBy = \Yii::$app->user->identity->id;
        $this->ModifiedOn = time();
    }
    return parent::beforeSave($insert);
}
like image 138
topher Avatar answered Sep 28 '22 06:09

topher