2014-12-08 51 views
2

无效数据我试图完成以下任务:Symfony的2形式,包括自定义消息

$builder->add('some_field', 'some_type', array(
    // ... 
    'invalid_message'   => 'You entered an invalid value: %1%', 
    'invalid_message_parameters' => array('%1%' => ?), 
)); 

我的问题是,我想不出哪里获取%1%的价值。

从阅读文档和搜索这是我想出了。有没有其他的方式来实现这一点?

回答

0

如果您再次查看文档,您会看到您在此处复制的特定示例仅适用于某些formType(如整数),并非用于执行您想要实现的功能。

阅读this first。你有很多约束的例子,以及如何设置正确的错误信息。

从你的代码中,你不能猜测你想要做什么,因为没有任何Contraint定义输入值是无效的。 我建议做验证的实体,如果你能做到这一点,这样你就可以让他们在资源/配置/ validation.yml

然后,你可以这样做:

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

价值在哪里会打印你想要的。如果你需要的话,你可以定义一个custom Constraint

0

如果您的表单基于实体,则应使用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',你只能使用'消息'。

0

如果你喜欢我正在寻找验证信息来设置投掷TransformationFailedException,你可以简单地使用由Symfony预先填充的{{ value }}

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