Symfony 2:仅验证已定义字段的表单

时间:2014-10-21 16:02:01

标签: forms symfony

是否可以仅验证表单的当前字段..

例如,我有一个declarationForm,我在validation.yml中为3个字段提供规则:name,reference,commantary ..有时我不在我的构建器中添加注释字段。无论如何,当我验证表格时,它说评论不能为空(但没有现场评论)

2 个答案:

答案 0 :(得分:1)

是的,但您必须从NotBlank validation.yml字段中移除commentary条件,并在将FormBuilderInterface字段包含在{{1}中时将其添加回构建器中}}:

$builder
    // ... other fields using add()
    ->add('commentary', 'text', array(
        'required' => true,
    ))
;

但请注意,这确实只会为requiredinput标记添加HTML5 label属性。

感谢@Cerad的更好的解决方案是add validation groups to your validation.yml字段:

AcmeBundle\Entity\Declaration: # change to your entity class
    properties:
        # ...
        commentary:
            - NotBlank: { groups: [commentaryReq] }

然后在需要时use the Form Builder with this validation group

$form = $this->createFormBuilder($declaration, array(
    'validation_groups' => array('commentaryReq'),
))
    //->add(...)
;

或者如果您正在使用表单类:

use Symfony\Component\OptionsResolver\OptionsResolverInterface;

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'validation_groups' => array('commentaryReq'),
    ));
}

如果有帮助,您还可以specify groups based on submitted dataspecify groups based on the button that was clicked

答案 1 :(得分:0)