php - Symfony 表单验证 : require field if another field is not empty

标签 php symfony symfony-forms symfony-validator

我使用 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/

相关文章:

php - Laravel 5.4 - "DB:raw()"使用 MySQL "CAST()"函数

php - 访问子类中的父属性值

java - 如何促进服务器上的 php 脚本与另一台服务器上正在运行的 Java 应用程序之间的通信?

php - 查询生成器 - 获取另一个查询的行数

php - 在 Symfony3 上验证文件扩展名

php - 为 Symfony 选择字段中的每个选项添加不同的 HTML 属性

javascript - jQuery AJAX 发送的 JSON 对象的 post 方法中未定义索引

php - 如何从 Controller Symfony2 内部访问不同的 Controller

php - 如何将 Symfony 形式的 MoneyType 输入覆盖为 ="number"类型?

forms - 自定义 sfWidgetFormDoctrineChoice 的布局