How To Setup Default Rules For All The Models?

In an application I’m working on, every table has the same common columns - creator_id, updater_id, date_created, last_updated. I want to be able to have default rules and relations for these columns in my models. In order to achieve that, there is EActiveRecord (that extends CActiveRecord) class and all other models inherit from that.

What I want to do is to use rules function in the child classes without merge and it automatically merged the parent rules to it? I have achieved that when using relations by calling getMetaData()->addRelation in the class, so the child classes just define a ‘relations’ function and its all good.

So, far I have created an abstract defaultRules class in the parent and the children have to use the defaultRules and everything works perfectly. But it would be more optimal if I can use the rules function. Is that even possible? I dug through the source of CModel and found out that its calling the rules function to achieve that… Is there a way to have addRule function in the class that I can use? (extensions will be fine too)

  • Gasim

Well, before you do that.

Do you rely on user input to set those rows? Because if you don’t I would not make rules. Simply set them in a model behavior (best) or controller method (okay) and forget validation.

If you must do what you are proposing you will need to write a custom methods in your base class to merge rules, and call the merge method from your child models that inherit from it.

The models need to be updated automatically, which happens in beforeSave:


public function beforeSave() {

   if($this->isNewRecord) {

      $this->date_created = new CDbExpression('NOW()');

      $this->creator_id = Yii::app()->user->id;

   }

   $this->updater_id = Yii::app()->user->id;

   return parent::beforeSave();

}

The user cannot set any of these values. But if I don’t set them up in the rules will it not update because their rules aren’t defined?

  • Gasim