How To Use Cdbexpression('now()') In Rules?

What is the Yii2 command for

 public function rules() {

	return [

array('create_time', 'default', 'value' => new CDbExpression('NOW()'), 'setOnEmpty' => false, 'on' => 'insert'),




I usually put that in my beforeSave() method:

public function beforeSave($insert)


        if (parent::beforeSave($insert)) {

            if ($this->isNewRecord) {

                $this->create_time = new \yii\db\Expression('NOW()');


            return true;



Or you can use the yii\behaviors\AutoTimestamp behavior for this. See ( for an example.

intead of CDbExpression(‘NOW()’) use \yii\db\Expression(‘NOW()’)

but in general for timestamps it is better to put them not in rules because rules are for user input. does your user really enter a creation_date in the form?

1 Like

I feel using [font="Courier New"]yii\behaviors\AutoTimestamp[/font] may be a better approach - offers flexibility of extending your code in future… you can use an expression like cebe mentioned… or your own callback function to get the timestamp… otherwise gracefully degrades to the PHP time() function