如何让 ZF2 字段集验证工作?

How to get ZF2 fieldset validation working?

我有一个简单的表单,目前只包含一个字段集。现在我希望对字段进行过滤和验证。所以我在 Fieldset class:

中实现了方法 getInputFilterSpecification()
...

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
            ]
        ];
    }
}

并将 Fieldset 添加到 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'
            )
        ));

    }
}

问题是,InputFilter 规范被完全忽略了。我已经在 FooFieldset#getInputFilterSpecification() 中设置了一个断点,并确保甚至用 die() 检查了它——该方法没有被调用。

这里有什么问题以及如何让它正常工作?

您将需要implement Zend\InputFilter\InputFilterProviderInterface interface in order for the getInputFilterSpecification() method to be called.