Yii Model Before Save

beforeSave()

class Mytable extends CActiveRecord
{
// Format 1
    public function beforeSave() 
    {
        if($this->isNewRecord)
        {           
            $this->createddate=new CDbExpression('NOW()');
        }else{
             $this->modifieddate = new CDbExpression('NOW()');
        }
        return parent::beforeSave();
    }
 
    // Format 2
    public function beforeSave() 
    {
        if($this->isNewRecord)
        {           
            $this->createddate=new CDbExpression('NOW()');
        }
        $this->modifieddate = new CDbExpression('NOW()');
        return parent::beforeSave();
    }
}

Before save method is called before the record saved in database. When we update record in table, Some fields are changed by default like record created date, record modified date etc. I wrote the sample code for record created and last modified.

In Format 1, If $this->isNewRecord is return true, it is new record. Now “createddate” variable will get current date. If $this->isNewRecord is return false, It will affect “modifieddate” date only

In Format 2, In this code, created date will affected only on new record. “modifieddate” will affected on when recored created or When record  modified

This function reduce our workflow. It is very helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *