Symfony FormType至少选择了一个无线电

时间:2018-06-14 13:34:58

标签: php forms symfony symfony-forms multiple-choice

我正在研究Symfony 3.4,我有一个FormType,其中包含多个字段和2个布尔值,如:

           ->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"
                )
            ))

因此用户可以在我的表单上选择2个布尔值是/否,我需要的是验证(后端的PHP验证,而不是前面的),就像选择了这两个布尔值中的至少一个一样。

因此,如果两者都设置为NO,则会出现错误'您必须至少选择first_boolean或second_boolean“

最好的方法是什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您只有表单类型且没有基础表单类型,那么您可以添加一个简单的Expression constraint

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',
                ))
            ]
        ));
}

注意表达式中的第二个或如何包含对其他字段的引用。这样两个字段都得到了"错误"。如果这太多了,你可以删除一个约束,只有一个字段突出显示错误。

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

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

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