phpzend-framework2zend-formzend-inputfilterinput-filter

How to get ZF2 fieldset validation working?


I have a simple form currently consisting of a single fieldset. Now I want the fields to be filtered and validated. So I implemented the method getInputFilterSpecification() in my Fieldset class:

...

class FooFieldset extends \Zend\Form\Fieldset
{

    public function __construct($name = null, $options = array())
    {
        parent::__construct($name, $options);

        $this->setHydrator(new ClassMethods(false));
        $this->setObject(new Buz());

        $this->setLabel('Baz');

        $this->add(array(
            'type' => 'text',
            'name' => 'bar',
            'options' => array(
                'label' => _('bar')
            )
        ));
    }

    public function getInputFilterSpecification()
    {
        return [
            'bar' => [
                'required' => true,
                'filters' => [
                    0 => [
                        'name' => 'Zend\Filter\StringTrim',
                        'options' => []
                    ]
                ],
                'validators' => [],
                'description' => _('bar lorem ipsum'),
                'allow_empty' => false,
                'continue_if_empty' => false
            ]
        ];
    }
}

and added the Fieldset to the Form:

...

class BuzForm extends \Zend\Form\Form
{

    public function __construct($name = null, $options = array())
    {
        parent::__construct($name, $options);

        $this->setAttribute('role', 'form');

        $this->add(array(
            'name' => 'baz-fieldset',
            'type' => 'Buz\Form\BazFieldset'
        ));

        $this->add(array(
            'type' => 'submit',
            'name' => 'submit',
            'attributes' => array(
                'value' => 'preview'
            )
        ));

    }
}

The problem is, that the InputFilter specifications are completely ignored. I've set a breakpoint into FooFieldset#getInputFilterSpecification() and to be sure even checked it witha die() -- the method is not called.

What is wrong here and how to get it working correctly?


Solution

  • You will need to implement Zend\InputFilter\InputFilterProviderInterface interface in order for the getInputFilterSpecification() method to be called.