Symfony2 表单:自动为必填字段添加 NotBlank 约束和引导验证器消息


Symfony2 form: automatically add NotBlank constraint and Bootstrap Validator message for required fields

在Symfony2中构建表单时,使用必填字段的验证和自定义错误消息,我必须手动指定NotBlank约束和自定义错误消息属性以进行客户端验证(使用Bootstrap Validator)。每个表单字段的代码如下所示:

$builder->add('name', 'text', array(
    'required' => true,
    'constraints' => array(
      new NotBlank(array('message' => 'Bitte geben Sie Ihren Namen ein.')),
    ),
    'attr' => array(
      // This is for client side bootstrap validator
      'data-bv-notempty-message' => 'Bitte geben Sie Ihren Namen ein.'
    )
));

我正在寻找通过仅指定一次required_message来缩短它的可能性:

$builder->add('name', 'text', array(
    'required_message' => 'Bitte geben Sie Ihren Namen ein.'
));

我希望构建器创建 NotBlank 约束和数据 bv-notempty-message 属性。

实现这一目标的最佳方法是什么?通过创建表单类型扩展?

我目前使用的解决方案如下: 在我的窗体的类型类中(或者在控制器类中,如果在没有 Type 类的情况下动态创建窗体),我添加一个用于添加必填字段的私有函数addRequired,如下所示:

class MyFormWithRequiredFieldsType extends AbstractType
{
    private $builder;
    private function addRequired($name, $type = null, $options = array())
    {
        $required_message = 'Bitte füllen Sie dieses Feld aus';
        if (isset($options['required_message'])) {
            $required_message = $options['required_message'];
            unset($options['required_message']);
        }
        $options['required'] = true;
        $options['attr']['data-bv-notempty-message'] = $required_message;
        if (!isset($options['constraints'])) {
            $options['constraints'] = array();
        }
        $options['constraints'][] = new NotBlank(array(
            'message' => $required_message
        ));
        $this->builder->add($name, $type, $options);
    }
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $this->builder = $builder;
        $this->addRequired('name', 'text', array(
            'required_message' => 'Bitte geben Sie Ihren Namen ein'
        ));
    }
}

这有效,但我不喜欢这个解决方案的是,为了添加必填字段,我必须调用$this->addRequired()而不是$builder->add(),因此我失去了链接add()调用的可能性。这就是为什么我正在寻找一种透明地覆盖$builder->add()方法的解决方案。