我使用 Symfony 5.3。我有一个包含 3 个字段的表单,这些字段未映射到任何实体:
- “原因”- 文本,
- “use_predefined”- 复选框
- “predefined_reason”- 下拉菜单。
我构建这样的表单(片段):
...
public function build(FormBuilderInterface $builder)
{
$builder->add('reason', TextareaType::class, [
'label' => 'Reason',
'required' => true,
'mapped' => false,
]);
$builder->add('use_predefined',
CheckboxType::class, [
'label' => 'Use predefined reason',
'required' => false,
'mapped' => false,
]);
$builder->add(
'predefined_reason',
ChoiceType::class,
[
'choices' => [
'option 1' => 1,
'option 2' => 2,
'option 3' => 3,
'option 4' => 4,
],
'expanded' => false,
'mapped' => false,
'label' => 'some label',
'required' => false,
]
);
}
...
“原因”字段应按要求显示在 UI 中,但其他两个字段不应显示。但是,在验证过程中,如果选中复选框“predefine_reason”,则第一个字段不应为必填项,而“predefine_reason”则应为必填项。
最佳答案
您应该能够使用Expression断言您的属性(property)是否有效。
/**
* @Assert\Expression(
* "(this.getUsePredefined() == true) or (this.getUsePredefined() == false and this.getReason() != null)",
* message="UsePredefined is not checked so reason is required"
* )
*/
protected $reason;
protected $use_predefined;
/**
* @Assert\Expression(
* "(this.getUsePredefined() == true and this.getPredefinedReason() != null) or (this.getUsePredefined() == false)",
* message="Error message"
* )
*/
protected $predefined_reason;
不要忘记编辑您的表单,并在不需要时删除必填字段,因为它们将在表单验证中进行验证。
如果你想要更动态的东西,你可能必须使用 javascript。
您还可以创建 custom contraint做类似的事情。
关于php - Symfony 表单验证 : require field if another field is not empty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70349767/