基于提交的数据的Symfony2表单验证组 [英] Symfony2 form validation groups based on submitted data

查看:37
本文介绍了基于提交的数据的Symfony2表单验证组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复杂的表单,有几个子表单,并且我希望能够根据在主表单中选择的单选按钮来分别验证每个子表单.我想通过验证组来实现这一目标.

I have some complex form, with several subforms, and I want to be able to validate each subform separately depending on radio button choosen in main form. I wanted to achieve this with validation groups.

注意:我没有 data_class 模型,我使用数组.

Note: I have no data_class model, I work with arrays.

这是我的表格简化了:

class MyType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('xxx', 'text', array(
                'constraints' => array(
                    new Constraints\NotBlank(),
                ),
                'validation_groups' => array(
                    'xxx',
                )
            ))
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'validation_groups' => function(FormInterface $form) {
                return array('xxx');
            },
        ));
    }
}

问题在于此字段的验证未触发.

The problem is that validation for this field is not triggered.

这可行时,我可以轻松地更改 setDefaultOptions ,以根据提交的数据来验证所需的组:

When this works, I can easily change setDefaultOptions to validate desired group depending on submitted data:

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'validation_groups' => function(FormInterface $form) {
            $data = $form->getData();

            return array($data['type']);
        },
    ));
}

有什么主意吗?

推荐答案

您必须将验证组名称传递给约束,而不是表单本身.通过将组名分配给表单,您可以指定在验证中使用哪些约束.

You have to pass the validation group name to the constraint, not in the form itself. By assigning group name to a form you specify which constraints to use in validation.

替换

$builder->add('xxx', 'text', array(
        'constraints' => array(
            new Constraints\NotBlank(),
        ),
        'validation_groups' => array(
            'xxx',
        )
    ))
;

使用

$builder->add('xxx', 'text', array(
        'constraints' => array(
            new Constraints\NotBlank(array(
                'groups' => 'xxx'
            )),
        ),
    ))
;

默认情况下,约束具有" Default "(大写)组,并且表单使用该组来验证是否未指定.如果您希望没有显式组的其他约束条件得到验证,请与指定组一起传递" Default "一个.

By default, constraints have the 'Default' (capitalized) group and forms use this group to validate if none specified. If you want the other constraints with no explicit group to validate, along with specified group pass the 'Default' one.

$resolver->setDefaults(array(
    'validation_groups' => function(FormInterface $form) {
        $data = $form->getData();

        return array($data['type'], 'Default');
    },
));

这篇关于基于提交的数据的Symfony2表单验证组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆