3
votes

Until now I have been binding input filters to the form in the module, in other words I have been creating elements in the form, adding input filters to the elements on the module side.

For example check this example

Right now im creating text field elements dynamically depending upon the requirements, like this in my form

//Form
public function addNamesTextFieldElement($names)
    {
        foreach($names as $name)
        {
            $nameTextField = new Element\Text($name->getName());
            $nameTextField->setAttribute('type', "text");
            $nameTextField->setLabel($name->getName());

            $this->add($nameTextField );
        }
    }

What would be best approach where to add/attach input filters to such dynamically generated elements.

1

1 Answers

0
votes

I probably wouldn't use this approach, but something like this would work, providing you have already assigned an InputFilter to the form:

public function addNamesTextFieldElement($names)
{
    $factory     = new InputFactory();
    foreach($names as $name)
    {
        $nameTextField = new Element\Text($name->getName());
        $nameTextField->setAttribute('type', "text");
        $nameTextField->setLabel($name->getName());

        $this->add($nameTextField );

        $this->getInputFilter()->add(
            $factory->createInput(array(
                'name'     => $name->getName(),
                'required' => true,
                'filters'  => array(
                    array('name' => 'StripTags'),
                    array('name' => 'StringTrim'),
                ),
                'validators' => array(
                    array(
                        'name'    => 'StringLength',
                        'options' => array(
                            'encoding' => 'UTF-8',
                            'min'      => 1,
                            'max'      => 100,
                        ),
                    ),
                ),
            ))
        );
    }
}