Search code examples
phpvalidationzend-formzend-framework3zend-inputfilter

Zend Framework collection validation


I am using Zend Framework 3 and I'm trying to validate a form with a collection field.

My form has a field

$this->add([
    'name' => 'domains',
    'options' => [
        'target_element' => [
            'type' => Text::class
        ]
    ],
    'type' => Collection::class
]);

When I submit the form I obtain something like this as POST data

[
    'domains' => [
        0 => 'first'
        1 => 'second'
    ]
]

I am trying to validate this with a CollectionInputFilter like the following

$filter = new InputFilter();
$filter->add([
    'type' => CollectionInputFilter::class,
    'options' => [
        'input_filter' => [
            'validators' => [
                [
                    'name' => Hostname::class
                ]
            ]
        ]
    ]
], 'domains');

$filter->setData($data);

but I obtain the exception Zend\InputFilter\CollectionInputFilter::setData expects each item in a collection to be an array or Traversable; invalid item in collection of type string detected.

What am I doing wrong?


Solution

  • I found out that the error was in using CollectionInputFilter. I should have been using ArrayInput instead.