php - 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 !
解决方案
好吧,如果您只有表单类型而没有基础表单类型,您可以添加一个简单的表达式约束:
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
在这种情况下,错误消息显示在表单级别。
推荐阅读
- python - 集成学习 Python-随机森林、SVM、KNN
- javascript - Jest 测试在 Github Action 上失败但在本地通过
- git - 为什么 git merge --no-commit 在我取消暂存时向我的历史记录添加了提交?
- javascript - Nodemailer 不适用于反应联系表
- html - 元素未正确定位
- java - Spring Batch 两次执行作业
- google-sheets - 如何从 Google 表格中的数据集创建新表?
- ipfs - IPFS:MFS 中的符号链接
- c - C99:访问全局变量和别名内存指针时的编译器优化
- powershell - 如何防止 PowerShell 脚本中的尾随换行符?