【问题标题】:Why Symfony2 form show the default error value notwithstanding the validation?尽管经过验证,为什么 Symfony2 表单仍显示默认错误值?
【发布时间】:2012-05-01 09:42:56
【问题描述】:

我正在继续研究 Symfony2,发现新的“问题”!

让我描述一下这个问题。 我有一个在 Doctrine Entity 上构造表单的类。它与this page of the official docs 中描述的注册表单示例相同。唯一的区别是我使用 Doctrine 而不是 MongoDB。

现在,我在 User 类中添加了以下字段

 /**
 * @Assert\Type(type="integer", message="Not an integer.")     
 * @ORM\Column(type="smallint", name="num")
 * 
 * @var Smallint $num
 * 
 */
protected $num; 

然后,我通过添加以下行更新了类 UserType 中的函数 buildForm

public function buildForm(FormBuilder $builder, array $options)
{
    ...
    $builder->add('num', 'integer', array(
        'label' => 'Insert a number',
        ));
}

这就是问题所在。尽管我通过 Annotation 提供了自定义消息,但字段 num(即字符串值)的错误输入会返回以下错误代码:“This value is not valid”而不是“不是整数”。

对自定义错误消息的这种遗漏解释有什么想法吗?

【问题讨论】:

    标签: forms symfony annotations doctrine-orm validation


    【解决方案1】:

    尝试添加

    'invalid_message' => "Not an integer'
    

    buildForm 方法中。

    【讨论】:

    • 是的,我知道!但它不一样。这只是一个技巧,而不是问题的答案。实际上,通过遵循此解决方案,您将为每个无效条目显示相同的错误消息。但是,通过 Annotation,您可以定义不同的错误类型。还是谢谢。
    • 那么你必须在buildForm方法中将字段设置为文本。 This value is not valid 是因为从 IntegerToLocalizedStringTransformer clientTransformer 抛出异常,在任何验证发生之前调用。
    猜你喜欢
    • 2015-01-03
    • 1970-01-01
    • 2014-11-28
    • 1970-01-01
    • 1970-01-01
    • 2013-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多