如何在 Symfony2 中的特定表单元素上分配验证组

How to assign a validation group on specific form element in Symfony2

我在 Symfony2 中有一个表单 class,我正在为表单的每个元素添加验证标准(而不是连接的实体对象)。我想向某些元素添加验证组,但我似乎无法弄清楚如何。

我指定如下形式的验证组:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'Acme\CommonBundle\Entity\Campaign',
        'validation_groups' => array('Default', 'new_title')
    ));
}

我在特定的表单元素上这样做:

->add('title', 'text', array(
    'required' => true,
    'help_text' => 'This is the title.',
    'constraints' => array(new NotBlank(), new Length(array('min' => 3, 'max' => 150))),
    'validation_groups' => array('new_title')

但是,这似乎不起作用。我做错了什么吗?

您可以将验证组分配给特定的表单元素 (as described in the docs for current symfony2 version),如下所示:

->add('title', 'text', array(
'required' => true,
'help_text' => 'This is the title.',
'constraints' => array(new NotBlank(array('groups' => array('new_title')), new Length(array('min' => 3, 'max' => 150, 'groups' => array('new_title')))),