如何设置 required 取决于 symfony 中的选择类型? [英] How to set required depends on choice type in symfony?

查看:24
本文介绍了如何设置 required 取决于 symfony 中的选择类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在有表单生成器中:

 $formBuilder->add('customDuplicatedId', TextType::class,
            [
                'required' => false,
                'data' => implode(",", $duplicatedIds),
                'mapped' => false,
                'help' => "Enter singleCheck Id separate by ',' "
            ]
        )
        ->add('isDuplicated', ChoiceType::class,
            [
                'required' => true,
                'data' => $entity->getSingleCheck()->isDuplicated(),
                'mapped' => false,
                'label' => 'Hidden (duplicated)',
                'expanded' => true,
                'choices'  => [
                    'Yes' => true,
                    'No' => false,
                ],
                'placeholder' => false
            ]);

我希望当用户选择Yes 时,需要输入文本.当用户选择 No 时,不需要输入文本.我该怎么做?

I would like when user choose Yes, the text input will required. When user choose No , the text input will not required. How can I do that?

推荐答案

您可以使用 回调 约束.这几乎就像定义一个自定义约束(如果您计划重用逻辑),但您可以直接在表单类型中使用闭包或其他可调用对象(检查参考).

You can do it by using a Callback constraint. It is almost like defining a custom constraint (and definitely the way to go if you plan on reusing the logic) but you can use a closure or other callable directly in the form type (check the reference).

->add('customDuplicatedId', TextType::class,
    [
        // Other options omitted
        'constraints' => new Callback(
            function($duplicateId, ExecutionContextInterface $context) {
                // Get the field we depend on by traversing the form
                // Current field: customDuplicateId
                $duplicated = $context->getObject()
                      // Parent: Form
                      ->getParent()
                      // Field isDuplicated -> value
                      ->get('isDuplicated')->getData();
                // 'choices' returns a bool in this case, so just apply logic
                if ($duplicated && empty($duplicateId)) {
                    $context->buildViolation('This value is required')
                        ->atPath('customDuplicatedId')
                        ->addViolation();
                }
            }
        ),
    ]
)

还可以以 defaults 形式全局设置约束,而无需将其绑定到特定字段并使用 context 访问目标.在这种需要访问多个字段的情况下,它可能会更清楚.在这种情况下,第一个参数将为空,getObject 将返回表单本身(因此无需调用 getParent).

It is also possible to set the constraint globally in the form defaults without binding it to an specific field and use the context to access the targets. In a case like this where you need access to multiple fields it might be clearer. In that situation the first argument will be empty and getObject will return the form itself (so there's no need to call getParent).

在自定义表单类型类中:

In a custom form type class:

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults([
        'constraints' => // ...
    ]);
}

在控制器中创建构建器(扩展 AbstractController):

Creating a builder in a controller (extending AbstractController):

$builder = $this->createFormBuilder($data, [ 'constraints' => /* ... */ ]);
$builder->add(/* ... */);

这篇关于如何设置 required 取决于 symfony 中的选择类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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