我正在尝试验证集合表单字段:
$builder->add(
'autor',
'collection',
array(
'type' => 'text',
'options' => array('required' => false),
'allow_add' => true,
'allow_delete' => true,
'by_reference' => false,
'error_bubbling' => false
)
);
我使用JavaScript,如Cookbook中所建议的,动态地向集合中添加更多文本字段。我的问题是,我不知道,如何验证这些字段。集合验证器允许我按名称验证集合的特定字段,但不仅仅是它的每个字段。我该如何管理?
如果可以检查,那么,如果至少其中一个字段是notBlank
而不是强制它到每个字段,那就更酷了。
祝你好运
答案 0 :(得分:5)
您可以使用在所有字段中可用的表单字段类型中定义的“约束”选项。(http://symfony.com/doc/master/reference/forms/types/form.html#constraints)。 在您的情况下,您可以添加如下约束:
$builder->add('autor', 'collection', array(
'constraints' => new NotBlank()),
));
(在这种情况下,不要忘记包含Validation组件提供的约束:
use Symfony\Component\Validator\Constraints\NotBlank;
...)
我没有测试,但我认为每次输入都会再次验证您分配给该字段的约束,并且因为您选择“error_bubbling”为false,则应将错误消息附加到无效元素。
<强> - 编辑 - 强>
由于您甚至使用2.0版本的Symfony,我认为此解决方案可以解决您的问题,但我强烈建议您更新到2.3版本。
您可以创建将监听POST_BIND事件的表单事件订阅者(http://symfony.com/doc/2.0/cookbook/form/dynamic_form_modification.html)。(请注意,Post Bind事件自版本2.3以后已弃用,将在3.0中删除);
在您的订阅者类中,您将根据需要验证每个提交的作者,并在出现错误时向表单添加错误。
你的postBind方法可能是这样的:
public function postBind(DataEvent $event)
{
$data = $event->getData();
$form = $event->getForm();
if (null === $data) {
return;
}
// get the submited values for author
// author is an array
$author = $form['autor']->getData();
// now iterate over the authors and validate what you want
// if you find any error, you can add a error to the form like this:
$form->addError(new FormError('your error message'));
// now as the form have errors it wont pass on the isValid() method
// on your controller. However i think this error wont appear
// next to your invalid author input but as a form error, but with
// this you can unsure that non of the fields will be blank for example.
}
如果您对核心方法有任何疑问,可以查看Symfony2表单组件API。 http://api.symfony.com/2.0/index.html