2

我有一个表单,我使用这样的注释生成器创建它:

$builder  = new AnnotationBuilder();
$fieldset = $builder->createForm(new \Application\Entity\Example());  
$this->add($fieldset);
$this->setBaseFieldset($fieldset);

在控制器中,一切都是标准的:

$entity = new \Application\Entity\Example();
$form = new \Application\Form\Example();
$form->bind($entity);
if($this->getRequest()->isPost()) {
    $form->setData($this->getRequest()->getPost());
    if($form->isValid()) {
        // save ....
    }
}

问题是,$form->isValid() 总是返回 true,即使提交的是空的或无效的表单。更奇怪的是,表单元素的错误信息都被设置了,暗示它们是无效的。

我查看了 ZF2 Form / InputFilter / Input 类,发现: Input->isValid() 被调用了两次:一次在 Form->isValid() 中,一次在 Form->bindValues() 中Input->isValid() ($this->getValidatorChain) 中的验证器链为空,在第二次调用(来自 bindValues)中它是正确的。

可能出了什么问题?

PS。使用开发版本 2.1

4

2 回答 2

1

我发现是什么原因造成的。

事实证明,注释构建器从未打算以这种方式工作。注释构建器创建了一个 \Zend\Form\Form 实例,我将其作为字段集放置在我的基本表单中。我不知道为什么,但这导致基本表单无法验证。所以为了使上面的代码工作,不应该有额外的 Form 类,在控制器中我们应该有:

$entity = new \Application\Entity\Example();
$builder  = new AnnotationBuilder();
$form = $builder->createForm($entity);  
$form->bind($entity);
if($this->getRequest()->isPost()) {
    $form->setData($this->getRequest()->getPost());
    if($form->isValid()) {
        // save ....
    }
}

或许未来 AnnotationBuilder 中会有一个 createFieldset 函数,但目前看来这是唯一的方法。希望这可以帮助某人。:)

于 2012-12-15T13:27:44.710 回答
0

我也遇到同样的问题。当我使用注释在表单中创建字段集@Annotation\Type("fieldset")时,isValid()始终返回 true。

查看Zend\Form\Factory的代码,当我们创建 Fieldset 时,configureFieldset()函数不会调用prepareAndInjectInputFilter() ,即使在表单规范 中有input_filter的地方也是如此。

只有在我们创建表单时,Zend\Form\Factory::configureForm()函数才会调用prepareAndInjectInputFilter()

因此,输入过滤器和验证组似乎仅由 AnnotationBuilder 在其类型设置为创建表单时创建。

我自己创建了一个输入过滤器,通过将下面的代码添加到我的表单中的注释:

    $fspec = ArrayUtils::iteratorToArray($builder->getFormSpecification($entity));
    $outerfilter = new InputFilter();
    $iffactory = new \Zend\InputFilter\Factory ();
    $filter  = $iffactory->createInputFilter($fspec['input_filter']);
    $outerfilter->add($filter, 'shop');  // Use the name of your fieldset here.
    $this->setInputFilter($outerfilter);
于 2014-08-04T22:50:10.933 回答