【问题标题】:Symfony 4 CollectionType Constraints - array of stringsSymfony 4 CollectionType 约束 - 字符串数组
【发布时间】:2020-07-30 18:08:44
【问题描述】:

我有一个非常简单的字符串数组,存储在数据库中并通过 API 提供。

使用 Symfony 的表单类型,我正在为各种数据添加验证。

我遇到了CollectionType 本质上是一个字符串数组的问题,例如:

['key', 'words', 'are', 'the', 'best']

附表格代码:

->add('keywords', CollectionType::class, [
    'allow_add' => true,
    'constraints' => [
        new Count(['min' => 1]),
        new NotBlank(['allowNull' => false])
    ]
])

这允许以下内容通过约束:

[null] 和 ['']

如果我能弄清楚我做错了什么,我也想为每个元素添加正则表达式验证。

【问题讨论】:

    标签: php json forms symfony validation


    【解决方案1】:

    如果您只想删除空元素,delete_empty 应该可以解决问题,您可以删除 NotBlank。

    要对元素应用额外的验证,您必须使用entry_options 将约束传递给集合item,而不是集合本身:

    ->add('keywords', CollectionType::class, [
      'allow_add' => true,
      'delete_empty' => true,
      'constraints' => [
        new Count(['min' => 1]),
      ],
      'entry_options' => [
        'constraints' => [
          new Regex(['pattern' => '/whateverpattern/']),
        ],
      ],    
    ])
    

    【讨论】:

    • 太棒了!我从 2.8 开始就一直在使用 Symfony,但我没有弄清楚这一点。效果很好,谢谢:)
    猜你喜欢
    • 2017-02-26
    • 2021-02-24
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 2017-01-15
    • 1970-01-01
    相关资源
    最近更新 更多