Forms Symfony 2表单在自定义消息中包含无效数据

Forms Symfony 2表单在自定义消息中包含无效数据,forms,symfony,Forms,Symfony,我正在努力实现以下目标: $builder->add('some_field', 'some_type', array( // ... 'invalid_message' => 'You entered an invalid value: %1%', 'invalid_message_parameters' => array('%1%' => ?), )); 我的问题是,我不知道从哪里获取%1%的值 通过阅读文档和搜索,我想

我正在努力实现以下目标:

$builder->add('some_field', 'some_type', array(
    // ...
    'invalid_message'            => 'You entered an invalid value: %1%',
    'invalid_message_parameters' => array('%1%' => ?),
));
我的问题是,我不知道从哪里获取%1%的值


通过阅读文档和搜索,我想到了这一点。是否有其他方法可以实现这一点?

如果您再次查看文档,您将看到您在此处复制的特定示例仅适用于某些表单类型(作为整数),而不适用于您想要实现的操作

阅读。这里有很多约束示例以及如何设置正确的错误消息

从您的代码中,您无法猜出您想要做什么,因为没有任何约束定义输入值无效。 如果可以的话,我建议在实体中进行验证,这样就可以将它们保存在Resources/config/validation.yml中

然后,您可以执行以下操作:

Acme\BlogBundle\Entity\Author:
properties:
    email:
        - Email:
            message: The email "{{ value }}" is not a valid email.

其中value将打印您想要的内容。这样,如果需要,可以定义约束。

如果表单基于实体,则应使用validation.yml文件来使用约束。如果没有(或者您很懒),也可以使用php在表单中添加约束,如下所示:

#Load the constraint you are going to use (for example length, which put min or max limits to your input length
use Symfony\Component\Validator\Constraints\Length;
# ...
#then in your controller or formtype where you build your form:
$form=$this->createFormBuilder()
        ->add('newPassword', 'password', array(
            'required' => true,
            'constraints' => array(
                new Length(array(
                    'min' => 8,
                    'minMessage' => 'You have entered {{ value }} which is under the limit length {{ limit }}')))))
        ->getForm();

在本例中,我构建了一个密码输入,它必须高于限制(8)。注意我是如何在这个输入中实现
length
约束的。然后使用
{{value}}
访问输入的值来打印消息。您应该了解不同的约束是如何实现消息的,在“长度约束”的情况下,您可以为其他约束设置“minMessage”和“maxMessage”,您只能使用“message”。

如果您和我一样正在搜索要在抛出
TransformationFailedException时设置的验证消息,您可以简单地使用由Symfony预先填充的
{{value}}

$builder->add('some_field', 'some_type', array(
    // ...
    'invalid_message' => 'You entered an invalid value: {{ value }}'
));