Invalidate Fields from Multiple Models

826 Views Asked by At

I have a form with multiple models in it. The validates in the models seems correct and the models are associated properly. But how do I invalidateFields from two models and pass the display error back to the form?

Code in my users)_controller.php is:

$errors = $this->User->invalidFields(array('fieldList' => array('password','cpassword','firstname','lastname','email')));

$this->User->set('errors',$errors);

But I have a Profile model chained like this:

$this->User->Profile

and want it to invalidFields to Profile.zip.

2

There are 2 best solutions below

2
On

Instead of manually setting errors in the invalid fields array, I would suggest to use the $validate array to set up validation rules.

You can define your own, complex rules if the built in ones are not enough.

0
On

you can use chained if clauses like described at http://www.dereuromark.de/2010/10/09/about-php-basics-and-pitfalls/

basically, you use & instead of &&

so if you got a main model and related data:

$this->User->set($this->data);
$this->User->Profile->set($this->data);
if ($this->User->validates() & $this->User->Profile->validates()) {
    //continue
}

the single & makes sure that both conditions are executed (with && you would only trigger the first one if there was an error and therefore the validation rules would not get rendered for the related model)

you could also do:

$val1 = $this->User->validates();
$val2 = $this->User->Profile->validates();
if ($val1 && $val2) {}

this way they both get executed before you go into the if clause.