cakePHP: how set error validation to input field manually in controller
20,693
Solution 1
if the $validate is defined in the model, bindModel wont cause closs of $var validate.
As for you primary question; you can set/unset/update $validationErrors of the models..eg
($remainTime < 30) {
$this->Model->validationErrors['limitTime'] = "time is less than 30";
}
Solution 2
This can be achieved using the invalidate method that will flag the field as having an error:-
$this->Model->invalidate('field_name', 'error message');
Solution 3
If you want to invalidate an associated model, you can use something like this:
$this->Model1->Model2->invalidate('Model2', __("Your validation message"));
In my case it invalidates associated select multiple (HABTM) field.
Author by
meotimdihia
Updated on August 21, 2020Comments
-
meotimdihia over 3 years
I want set error validation to input field manually in controller example:
if ($remainTime < 30) { ..... set error validation in here (error: limitTime ), ( error is not in model ) }
other question: i want to ask : bindModel ( in this case , I use bindModel in Behaviors ) 'll cause loss of relationship with other model but is bindModel cause loss of $var validate,too ?
-
meotimdihia over 13 yearsno, i want set error validation , in this case, $validate == null
-
Nik Chankov over 13 yearsDo you want to invalidate a field, or just to show that the form in general is invalid?
-
alecho over 9 yearsThis is probably the more correct answer as this calls the Validator method that does almost the same thing as the currently accepted answer. See the 2.6 API docs here: api.cakephp.org/2.6/source-class-ModelValidator.html#278-288
-
drmonkeyninja over 8 years@neobie this is the correct way of invalidating a field in CakePHP 2.x. If this isn't working for you, you are probably doing something else wrong.
-
Álvaro González over 5 yearsPlease note that standard validators reset validation messages so
invalidate()
results are destroyed if you perform further validations.