Difference between #8 and #9 of
How to automate timestamps in ActiveRecord models

Revision #9 has been created by Maurizio Domba Cerin on Jun 17, 2011, 10:16:17 AM with the memo:

changed text to mention Gii instead of yiic, and explained better the beforeSave() variant
« previous (#8) next (#10) »

Changes

Title unchanged

How 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. Two ways you can dof thisem are: 1. Via rules() 2. Via beforeSave() 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 gener
;
 
 
After we have the table we need to cre
ate thea model with the Yii shell tool:
 
 
    model Node Nodes
 
 
To create the crud functionality we need to type this:
 
 
    crud Node
and CRUD for it by using Gii.
 
 
Check the guide on [How to generate model and 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.
[...]
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 solutions to this issue.
25 0
35 followers
Viewed: 153 996 times
Version: 1.1
Category: Tutorials
Tags:
Written by: dalip
Last updated by: Yang He
Created on: Feb 14, 2009
Last updated: 5 years ago
Update Article

Revisions

View all history