Using Validation Rules Of Models In Form
Posted 07 April 2014 - 03:22 PM
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.
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?
Posted 07 April 2014 - 03:29 PM
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.
Posted 07 April 2014 - 04:46 PM
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.