thomas-peter
thomas-peter

Reputation: 7944

How do I add an entry to InputFilter when using a Collection?

I want to filter and validate each item and validate the whole to check there are no duplicates. There is an arbitrary amount of text inputs in the collection.

    $this->add(array(
        'type' => 'Zend\Form\Element\Collection',
        'name' => 'aliasList',
        'options' => array(
            'label' => 'Alias',
            'count' => 2,
            'allow_add' => true,
            'target_element' => array(
                'type' => 'Zend\Form\Element\Text'
            )
        )
    ));

I tried adding the code below, but I was crossing my fingers pretty hard. It obviously didn't work. It was hoping there might be an option such as 'oneach' = true.

    $inputFilter->add($factory->createInput(array(
        'name' => 'aliasList',
        'required' => false,
        'filters' => array(
            array('name' => 'StripTags'),
            array('name' => 'StringTrim'),
        ),
    )));

I also intend on adding validators for valid URI and to fail on duplicate. Unfortunately as I'm using ZF2 I think I'm going to be waiting a long time for another ZF2 s̶u̶f̶f̶e̶r̶e̶r̶ developer to come along.

Upvotes: 1

Views: 2508

Answers (2)

Anatoly E
Anatoly E

Reputation: 1141

You can use smt like:

 $inputFilter = new InputFilter();
 $inputFilter->add($factory->createInput(array(
    'name' => 'aliasList',
    'required' => false,
    'filters' => array(
        array('name' => 'StripTags'),
        array('name' => 'StringTrim'),
    ),
 )));

 $collectionFilter = new CollectionInputFilter();
 $collectionFilter->setInputFilter($inputFilter);

Upvotes: 0

Sam
Sam

Reputation: 16455

This may not help your problem in a 1:1 ratio, but you may want to try to work around this by adding collections as a fieldset. In most cases anything you add into a collection is of a different type and therefore, just by logic, should be on a separate fieldset.

Therefore you may want to try that approach. I assume you know of that blog, in case not here's a very helpful link http://www.michaelgallego.fr/blog/?p=190

 $this->add(array(
    'type' => 'Zend\Form\Element\Collection',
    'name' => 'categories',
    'options' => array(
        'label' => 'Please choose categories for this product',
        'count' => 2,
        'should_create_template' => true,
        'allow_add' => true,
        'target_element' => array(
            'type' => 'Application\Form\CategoryFieldset'
        )
    )
));

This way you add Collection Elements from a Fieldset and the fieldset inputFilters and validators will be added via

public function getInputFilterSpecification() {}

from the Fieldset-Class.

Upvotes: 3

Related Questions