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

时间:2016-02-29 22:05:01

标签: php zend-framework2 zend-form zend-inputfilter input-filter

我有一个简单的表单,目前由一个字段集组成。现在我希望过滤和验证字段。所以我在getInputFilterSpecification()类中实现了Fieldset方法:

...

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()检查它 - 该方法未被调用。

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