How to validate array of form inputs in cakephp 2

I have this kind of array of inputs in view:
echo $this->Form->input(“Application.ref.$i”, …

Say $i=1…

How can I validate this in Model public $validate ? I tried ‘Application.ref.1’ but it does not seem to work… I did not find clues in the book…

What is “ref”? In this sort of structure, that’s typically going to be another entity with a hasMany or belongsToMany relation to the main entity (in which case the input name should have a plural there, like refs). If that’s the case, then the place to do that validation is in that other entity’s table.

Names can be misleading… Actually there are no relations, it’s just the naming. Only one model in this case. It could be e.g. “Myclub.member.1”. The point is that it is array of form inputs in the view and it works fine. Model: $this->data[‘Application’][‘ref’][0]

But I cannot find right validation syntax/way to access those entries… or should i make an my own function in my model to loop and check those data manually?

Maybe I have to get rid of that dot and use Application.ref1, Application.ref2… It’s more tedious but I cannot find the solution to arrays…

In cake 3 I had a similar issue and the solution may apply in 2.

I had a schema that I wanted to define using dot notation in a modelless form. The form helper took in the schema well enough, but the post back to my app was an expanded array and this made the post-data not match my validation rules which were expecting dot notation.

I used the Cake utility class method Hash::flatten($array) to satisfy the validators.

Later I had to expand the errors() that were returned from the validator to satisfy expectation of the form for error reporting.

I used an override of the Form::validate($data) call.

    public function validate($data)
    {
        $result = parent::validate(Hash::flatten($data));
        $this->setErrors(Hash::expand($this->getErrors()));
        return $result;
    }
1 Like