Skip to main content

yii, How to automate timestamps in ActiveRecord models


There are many ways to automate the setting of timestamps in yii ActiveRecord models. Two of them are:
  1. Via rules()
  2. Via beforeSave()
To start off we need to create a database table.
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`)
);
After we have the table we need to create a model and CRUD for it by using Gii.
The first way you can do it is via your model's rules. Here is 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 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.
Another solution is to use beforeSave() as follows:
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:
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.

Popular posts from this blog

Yii, return to previous url after login or logout

If you want to return to your previous url after login or logout try this : <?php $this -> redirect (Yii :: app () -> request -> urlReferrer ); ?> To set the return url to be the url that was before the login page or registeration page was called you can put following code in views/layouts/main.php file : <?php //this checks id the controller action is not 'login' then it keeps the current url in returnUrl if (CController :: getAction () -> id != 'login' ) { Yii :: app () -> user -> setReturnUrl (Yii :: app () -> request -> getUrl ()); } ?>

Yii2: Using csrf token

Yii2: Using csrf token First, if you do not understand what is the CSRF token? and why should we use it, please refer to the following link : https://www.owasp.org/index.php/Cross-Site_Request_Forgery_(CSRF) One of the new features of Yii2 is CSRF validation enabled by default. If you use ajax or basic form as follows : <form action='#' method='POST'> ........... </form> You will get an error exception : Bad Request (#400): Unable to verify your data submission That is because you do not submit csrf token. The easiest way if you dont care about csrf just disable it in main config : 'components' => [ 'request' => [ .... 'enableCsrfValidation'=>false, ], ..... ], Or in Controller : public function beforeAction($action) { $this->enableCsrfValidation = false; return parent::beforeAction($action); } So how to use Csrf Validation for your strong security website: * Wi