ZF2 nested data validation

243 Views Asked by At

I'm trying make to work my validation. I have data posted to controller in the format like this:

[
    'property' => 'value',
    'nested_property' => [
        'property' => 'value',
        // ...
    ]
]

I have divided fields/filters and form into different classes and just gather it together in the Form's controller that looks like that:

public function __construct($name, $options)
{
    // ...
    $this->add(new SomeFieldset($name, $options));
    $this->setInputFilter(new SomeInputFilter());
}

But it doesn't work properly, looks like it just ignores nested array (or ignores everything). What have I missed?

Thank you.

1

There are 1 best solutions below

0
Kwido On BEST ANSWER

You need to set up your inputfilter like the way you've setup your forms including the fieldsets if you use the InputFilter class.

So when you've got a structure like:

  1. MyForm
    1.1 NestedFieldset
    1.2 AnotherFieldset

Your inputfilters need to have the same structure:

  1. MyFormInputFilter
    1.1 NestedFielsetInputFilter
    1.2 AnotherFieldsetInputFilter

Some example code:

class ExampleForm extends Form
{
    public function __construct($name, $options)
    {
        // handle the dependencies
        parent::__construct($name, $options);

        $this->setInputFilter(new ExampleInputFilter());
    }

    public function init()
    {
        // some fields within your form

        $this->add(new SomeFieldset('SomeFieldset'));
    }
}

class SomeFieldset extends Fieldset
{
    public function __construct($name = null, array $options = [])
    {
        parent::__construct($name, $options);
    }

    public function init()
    {
        // some fields
    }
}

class ExampleInputFilter extends InputFilter
{
    public function __construct()
    {
        // configure your validation for your form

        $this->add(new SomeFieldsetInputFilter(), 'SomeFieldset');
    }
}

class SomeFieldsetInputFilter extends InputFilter
{
    public function __construct()
    {
        // configure your validation for your SomeFieldset
    }
}

So the important part of configuring your inputFilter for these situations is that you need to reuse the name of your fieldset when using: $this->add($input, $name = null) within your InputFilter classes.