全局覆盖symfony2.1上的NotBlank约束消息


Overwrite the NotBlank Constraint Message on symfony2.1 globally?

如何在整个Symfony 2.1应用程序中全局覆盖NotBlank约束消息This value should not be blank

我尝试过使用validators.en.yml文件,但只有当我将validation.yml文件中的每个NotBlank约束设置为类似not.blank.field的常量时,这才有效,但修改太多了。

要替换在应用程序级别触发NotBlank约束时显示的This value should not be blank消息,只需在正确的位置创建正确的翻译文件。

为了简单起见,您的语言环境似乎是英语(en),因此创建文件app/Resources/translations/validators.en.yml并在其中写入以下行:

# app/Resources/translations/validators.en.yml
This value should not be blank.: Y U NO SET THE VALUE?!

第一部分必须与您想要翻译的消息完全匹配(在您的案例中为This value should not be blank.)。

如果您有自定义的文件/文件夹层次结构,只需在<kernel root directory>/Resources/translations下创建文件即可。

如果你想对另一种语言(例如法语)有同样的行为,只需在同一文件夹中创建相应的文件:

# app/Resources/translations/validators.fr.yml
This value should not be blank.: La valeur doit etre specifiee.

添加新文件后,不要忘记清除缓存

为什么它有效?因为Symfony2按位置对翻译文件进行优先级排序:http://symfony.com/doc/current/book/translation.html#translation-位置和命名约定