Sunday, January 12, 2014

Use of beforeSave() and beforeValidate() for Yii models when writing to database

beforeValidate() is very handy for performing validation of the model before it is save to the database in Yii, below shows an example of how it is used in a Yii model class Project

protected function beforeValidate() 
{
 if($this->isNewRecord)
 {
  // set the create date, last updated date and the user doing the creating
  $this->audit_create_time=$this->audit_update_time=new CDbExpression('NOW()');
  $this->audit_update_time=new CDbExpression('NOW()'); 
  
  $existing_proj=Project::model()->find('projname=?', array($this->projname));
  if(isset($existing_proj))
  {
   return false;
  }
 }
 else
 {
  //not a new record, so just set the last updated time and last updated user id
  $this->audit_update_time=new CDbExpression('NOW()'); 
 }
 
 return parent::beforeValidate();
}
The above code checks whether a project with the same projname already exist in the database, if yes, then the validation return false, it also updates the create time and update time depending on whether the action is to create or update a project.

beforeSave() is useful to perform additional data processing before a model is saved to the database, below shows an example of how it is used in a Yii model class User

public function beforeSave()
{  
 if($this->isNewRecord)
 {
  $this->audit_db_create_time=$this->audit_db_update_time=new CDbExpression('NOW()');
 }
 else
 {
  $this->audit_db_update_time=new CDbExpression('NOW()'); 
 }
 
 $this->password=$this->encrypt($this->password);
 
 return TRUE;
}
The above code encrypt the password before it is saved to the database, it also updates the create time and update time for writing the model to the database depending on whether the action is to create or update a user

No comments:

Post a Comment