Monday, February 20, 2012

Make your own rule in yii framework

If you want to create new rules that doesn't meet to your spesification in your model you can create your custom rules in your model.

To accomplish this just simple add your custom function in your model. And then add the function in rules that you have created.

The example can be seen below code to define my custom function


public function beforeProjectStart($attribute,$params){
  $project=Project::model()->findByPk($this->project_id_FK);
  if(Utils::getDaysBetweenTwoDatesForModel($this->start_time_planned, $project->start_time_planned)<0)//jika start date pada components lebih besar dari start date dari project maka error
   $this->addError($attribute, "Start time component planned must be more than project start planned ".$project->start_time_planned);
 }
 public function beforeProjectEnd($attribute,$params){
  $project=Project::model()->findByPk($this->project_id_FK);
  if(Utils::getDaysBetweenTwoDatesForModel($this->end_time_planned, $project->end_time_planned)>0)//jika start date pada components lebih besar dari start date dari project maka error
  $this->addError($attribute, "End time component planned must be more than project end planned ".$project->end_time_planned);
 }

And then you can add your custom rules as below in your rules()
public function rules()
 {
  // NOTE: you should only define rules for those attributes that
  // will receive user inputs.
  return array(
  array('name', 'required'),
  array('start_time_planned','beforeProjectStart'),
  array('start_time_planned','beforeProjectEnd'),
That's simple to custom your own rules and add your custom message to your rules. Yii is ROck..

No comments:

Post a Comment