首页 > 解决方案 > Symfony FormType at least one radio selected

问题描述

I'm working on Symfony 3.4 and I have a FormType with multiples fields and 2 booleans like :

           ->add("is_my_first_boolean", ChoiceType::class, array(
                "expanded" => true,
                "multiple" => false,
                "choices" => array(
                    'Yes' => "1",
                    'No' => "0"
                )
            ))
            ->add("is_my_second_boolean", ChoiceType::class, array(
                "expanded" => true,
                "multiple" => false,
                "choices" => array(
                    'Yes' => "1",
                    'No' => "0"
                )
            ))

So the user can select 2 booleans Yes/No on my form, and what I need is a validation (PHP validation in back-end, not in front) like at least one of these two booleans is selected.

So if both are set to NO, there is an error 'You must choose at least first_boolean or second_boolean"

What's the best way to do that ?

Thanks !

标签: phpformssymfonysymfony-formsmultiple-choice

解决方案


好吧,如果您只有表单类型而没有基础表单类型,您可以添加一个简单的表达式约束

use Symfony\Component\Validator\Constraints as Assert;

....

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add("is_my_first_boolean", ChoiceType::class, array(
            "expanded" => true,
            "multiple" => false,
            "choices" => array(
                'Yes' => "1",
                'No' => "0"
            ),
            'constraints' => [
                new Assert\Expression(array(
                    'expression' => 'value == 1 or this.getParent()["is_my_second_boolean"].getData() == 1',
                    'message' => 'Either is_my_first_boolean or is_my_second_boolean must be selected',
                ))
            ]
        ))
        ->add("is_my_second_boolean", ChoiceType::class, array(
            "expanded" => true,
            "multiple" => false,
            "choices" => array(
                'Yes' => "1",
                'No' => "0"
            ),
            'constraints' => [
                new Assert\Expression(array(
                    'expression' => 'value == 1 or this.getParent()["is_my_first_boolean"].getData() == 1',
                    'message' => 'Either is_my_first_boolean or is_my_second_boolean must be selected',
                ))
            ]
        ));
}

注意表达式中的第二个 or 包含对另一个字段的引用。这样,两个字段都得到了“错误”。如果这太多了,您可以删除一个约束,并且只有一个字段突出显示错误。

如果您的表单由数据类支持,您当然可以将表达式约束添加到此类:

/**
 * @Assert\Expression(
 *     "this.getisMyFirstBoolean() or this.getisMySecondBoolean()",
 *     message="Either first or second boolean have to be set",
 * )
 */
 class MyFormData

在这种情况下,错误消息显示在表单级别。


推荐阅读