Monday, May 26, 2014

Re: callback succession / why afterValidate() if validation fails

Thx José for the explanation.

But how do I test if the validation has failed ?
Something like this is not really nice...

    function afterValidate($options) {
        if (!empty($this->validationErrors)) {
            return false;
        }
    }

any better idea ?
TIA,
Charles

On 26.05.14 10:16, José Lorenzo wrote:
It is just the way it works. There are equal amount of reasons for wanting the callback to be run after the validation has failed, can you not change the logic to check if there are any validation errors and not run the rest of the method?

On Monday, May 26, 2014 10:06:50 AM UTC+2, cbueche wrote:
Dear Bakers,

I have an app under CakePHP 2.5.1. I'm not sure to understand how the callback succession is supposed to work, eg if the validation fails, there is IMHO no reason to run afterValidate() ? But it does run indeed.

What I'm trying to do:

my form has 7 entry fields. The ones I have issues with are start_time, end_time and duration. The user might enter a combination of them, eg

- start & end
- start & duration
- duration & end
- only duration

(at the end, I only care about durations)

My strategy for saving the data is

- have a validation for the fields, eg to get the right time format (HH:MM) or duration, but with 'required' => false and 'allowEmpty' => true
- in afterValidate(), I verify that the new entered start and end do not overlap with existing records
- in beforeSave(), I verify the combination entered by the user, the goal being to calculate a duration

My problem is that even if the user enters a wrong format for a field, Cake still run afterValidate(), causing problems in my queries, before I can return "false" to abort the save.

Now I'm not really sure why cake runs afterValidate() if validation fails. Is there something I missed ?

TIA for your assistance,
Charles

No comments: