Changes
Title
changed
AHow to automate timestamps in ActiveRecord models
Category
unchanged
Tutorials
Yii version
unchanged
Tags
unchanged
Content
changed
There are
dozens ofmany ways to automate the setting of timestamps in yii ActiveRecord models
, for example with behaviours or onBeforeSave methods. I sort of like the following method.. Three are presented here:
1. Via rules()
2. Via beforeSave()
3. Via CTimestampBehavior (zii)
To start off we need
to create a database table.
[sql][...]
`modified` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
Following this we'll;
After we have the table we need to create a model and CRUD for it by using Gii.
Check the guide on [How to generate
the model
with the Yii shell tool:
model Node Nodes
To create the crud functionality we need to type this:
crud Node
The magic happens in the rules of the Node classand CRUD with Gii](http://www.yiiframework.com/doc/guide/1.1/en/quickstart.first-app#implementing-crud-operations "How to generate model and CRUD with Gii").
The first way you can do it is via your model's rules. Here is an example.
[php][...]
array('title','length','max'=>255),
array('title, created, modified', 'required'),
array('modified','default',
'value'=>new CDbExpression('NOW()'),
'setOnEmpty'=>false,'on'=>'update'),
array('created,modified','default',
'value'=>new CDbExpression('NOW()'),
'setOnEmpty'=>false,'on'=>'insert')
);
}[...]
You see the two rules at the end, one changes the modified field when the record's being updated, and the other changes both fields when the record's being created. You'll also see the "new CDbExpression('NOW()')" statement. This passes "NOW()" to the MySQL server and it will not be escaped. MySQL will interpret it as a statement and not as a string. This means that the field types could have been any other date/time type (timestamp, etc.) and it would still work.
I find it aAnother solution is to use beforeSave() as follows:
[php]
public function beforeSave() {
if ($this->isNewRecord)
$this->created = new CDbExpression('NOW()');
else
$this->modified = new CDbExpression('NOW()');
return parent::beforeSave();
}
Note that in the above code, when creating a new record only the 'created' field will be assigned/updated, while the 'modified' record will be assigned/updated only when updating an existing record.
If you want to assign/update the 'modified' field even when creating a new record... use this code:
[php]
public function beforeSave() {
if ($this->isNewRecord)
$this->created = new CDbExpression('NOW()');
$this->modified = new CDbExpression('NOW()');
return parent::beforeSave();
}
These are simple and elegant solution
s to this issue.
The third possibility is to use CTimestampBehavior in your models. You can read about this in the API documentation:
[http://www.yiiframework.com/doc/api/1.1/CTimestampBehavior](http://www.yiiframework.com/doc/api/1.1/CTimestampBehavior "Yii API: CTimestampBehavior")