Reputation: 571
I'm working with cakephp 2.0.2. I'm saving a relatively simple association of models. A Work model with a one-to-many association to images. I'm finding the validation of these two models to be working in an unpredictable manner.
When I make a save with a perfectly valid form:
$this->Work->saveAll($this->data);
I can get the data successfully saved, but when I call:
$this->Work->invalidFields();
I actually see failed validations for the Work model's rules even though the form should not have triggered them.
Array
(
[title] => Array
(
[0] => Please enter a title.
)
[copy] => Array
(
[0] => Please enter project copy.
)
)
Experimenting further with this. If I re-submit the form with the title field intentionally left blank, I'll get the following from my $this->Work->invalidFields()
call:
Array
(
[title] => Array
(
[0] => Please enter a title.
[1] => Please enter a title.
)
)
So, it seems by default the rule is displaying once regardless if its truly invalid or not. Then again if the field really is invalid.
Finally, for posterity, my simple validation rules:
public $validate = array(
'title' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'Please enter a title.'
),
'copy' => array(
'rule' => 'notEmpty',
'required' => true,
'message' => 'Please enter project copy.'
)
);
Any ideas on this strangeness? Thanks in advance!
Upvotes: 2
Views: 1472
Reputation: 4299
this answer from Mark-story:
Yes, this is how it works. Since you are using lower level methods the validationErrors are not reset. You should use create() + save() to automatically flush errors. Or if you just want errors, you should access the Models->validationErrors property instead of calling invalidFields().
Upvotes: 0
Reputation: 153
Calling Model->invalidFields() does not flush errors. If you need an array of invalid fields, you can use Model->validationErrors property instead.
Upvotes: 2
Reputation: 7465
Have you tried setting the data to the model's data array and then validating? My guess is that the validation needs to be explicitly called. However...you can browse through the cake model class in the lib folder to find out.
$this->Work->data = $data;
if($this->Work->validate()){
$this->Work->saveAll();
}
Upvotes: 0