Social Icons

Pages

Friday, March 29, 2013

Before Save Function in Model

beforeSave() -- model is a nice function in yii framework

When we update record in table, Some fields are changed by default like when record created, when record modified etc. Here I wrote code for this action. In Format 1, I configured separately for created date, modified date. $this->isNewRecord is return true, if it is new record. Now I affected date only If $this->isNewRecord is return false, I will affect modified date only. In Format 2, I configured both created date, modified date in beforeSave() function. In this code, created date will affected only on new record. modified date will affected on when recored created or When record modified This function reduce our workflow. Just make this function once It was very helpful.




class Mail extends CActiveRecord
{
    // Format 1
    public function beforeSave() 
    {
        if($this->isNewRecord)
        {           
            $this->date=new CDbExpression('NOW()');
            $this->status=0; //option by default
        }else{
             $this->modified = new CDbExpression('NOW()');
        }
        return parent::beforeSave();
    }

    // Format 2

    public function beforeSave() 
    {
        if($this->isNewRecord)
        {           
            $this->date=new CDbExpression('NOW()');
            $this->status=0; //option by default
        }
        $this->modified = new CDbExpression('NOW()');
        return parent::beforeSave();
    }
}










No comments:

Post a Comment