There are many ways to automate setting yII timestamps in the ActiveRecord model. Here are two methods:

  • Through the rules ()
  • Through beforeSave ()
We need to start building database tables.

CREATE TABLE IF NOT EXISTS `Nodes` ( `id` bigint(20) NOT NULL auto_increment, `title` varchar(255) NOT NULL, `created` datetime NOT NULL, `modified` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;


We will use the Yii shell tool to build the model as follows:

To create cruD functionality for model Node Nodes, we need to:

crud Node


The first way is through the rules of your model. Here’s an example.

/** * @return array validation rules for model attributes. */ public function rules() { return array( 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 end up with two rules, one for changing property values when updating records and the other for changing property values when creating records. You can also see the “new CDbExpression(“NOW()”) statement. This goes through the MySQL server of “NOW()” and it won’t be avoided. MySQL can translate this as a statement, not as a string. This means that the field type can be another date/time type (timestamp, etc.), and it still works.

Another solution is through the beforeSave() method, which uses the following:

public function beforeSave() { if ($this->isNewRecord) $this->created = new CDbExpression(‘NOW()’); else $this->modified = new CDbExpression(‘NOW()’); return parent::beforeSave(); }


These are simple and elegant ways to solve this problem.