Using Validation Rules Of Models In Form

Hi guys

I already searched but didn’t find the right topic. But I’m pretty sure I’m not the first one having this issue.

I have a form which collects data for different models. I set some validation rules in models as well as in the form. That works, sure.

BUT: You need to keep those rules in sync.

An Example:

Model A with rules for attributes a1 and a2

Model B with rules for attributes b1 and b2

Form X with rules for attributes a1, a2, b1 and b2.

I want to keep rules in model, but want to use the same in form to be sure that both validate the same stuff.

So what I thought would be nice to tell the form to use the validation rules from the corresponding models so that I only have to touch the model if I want to change the rules.

Or maybe just outsourcing the rules.

Does yii have that possibility built in or does someone has an idea how to solve that?

First of all: are you sure you really need extra form validation?

I mean, if ($a->validate() && $b->validate()) is usually enough.

Next, rules() is just a simple function returning the array of values, so you can call it and merge the result with whatever you need.

I think yes, I need it. You’re right, I could just validate the models, but then I won’t get the messages displayed on client. Therefore I have the rules also in the form.

Well, I thought also about just merging the results of the rules(). But since this is not a static method I would need to instantiate all models to get the rules. I would need a static method for that. So yes, I could move rules array into a static method and use this method in rules() and in my form.