在 Symfony 2 中验证动态加载的选择 [英] Validating dynamically loaded choices in Symfony 2

查看:23
本文介绍了在 Symfony 2 中验证动态加载的选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表单中有一个名为 *sub_choice* 的选择字段类型,其选择将通过 AJAX 动态加载,具体取决于名为 *parent_choice* 的父选择字段的选定值.加载选项工作正常,但在提交时验证 sub_choice 的值时遇到问题.它给出了此值无效"验证错误,因为提交的值在构建时不在 sub_choice 字段的选择中.那么有没有一种方法可以正确验证 sub_choice 字段的提交值?下面是构建我的表单的代码.我使用的是 Symfony 2.1.

I have a choice field type named *sub_choice* in my form whose choices will be dynamically loaded through AJAX depending on the selected value of the parent choice field, named *parent_choice*. Loading the choices works perfectly but I'm encountering a problem when validating the value of the sub_choice upon submission. It gives a "This value is not valid" validation error since the submitted value is not in the choices of the sub_choice field when it was built. So is there a way I can properly validate the submitted value of the sub_choice field? Below is the code for building my form. I'm using Symfony 2.1.

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('parent_choice', 'entity', array(
                    'label' => 'Parent Choice',
                    'class' => 'Acme\TestBundle\Entity\ParentChoice'
    ));

    $builder->add('sub_choice', 'choice', array(
                    'label' => 'Sub Choice',
                    'choices' => array(),
                    'virtual' => true
    ));
}

推荐答案

要做到这一点,您需要在提交表单之前覆盖 sub_choice 字段:

To do the trick you need to overwrite the sub_choice field before submitting the form:

public function buildForm(FormBuilderInterface $builder, array $options)
{
    ...

    $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
        $parentChoice = $event->getData();
        $subChoices = $this->getValidChoicesFor($parentChoice);

        $event->getForm()->add('sub_choice', 'choice', [
            'label'   => 'Sub Choice',
            'choices' => $subChoices,
        ]);
    });
}

这篇关于在 Symfony 2 中验证动态加载的选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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