What is the Yii2 command for
public function rules() {
return [
array('create_time', 'default', 'value' => new CDbExpression('NOW()'), 'setOnEmpty' => false, 'on' => 'insert'),
];
}
thanks
What is the Yii2 command for
public function rules() {
return [
array('create_time', 'default', 'value' => new CDbExpression('NOW()'), 'setOnEmpty' => false, 'on' => 'insert'),
];
}
thanks
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 (https://github.com/yiisoft/yii2/blob/1f6a8230732d829cdf2f3ca6755e4ac32f2c6f4f/apps/advanced/common/models/User.php) 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?
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