问题描述
当你使用 @Assert\NotBlank
约束并且给定的字段为空时,你会得到错误:
该值不能为空
我想在应用程序范围内更改此消息,而不更改 Symfony2 源代码.如何做到这一点?
剪切验证错误消息非常简单,但乍一看似乎很棘手.
默认语言环境
首先,您应该更改应用程序的默认语言环境.在 2.0.x 版本中,要更改的正确值是 framework.session.default_locale
.为了将来参考,从 2.1.0 开始,它将是 framework.default_locale
.请参阅文档以获得正确的语法.
区域设置应包含您的语言和地区,并定义为 language_REGION
(list语言,国家/地区列表).例如,在德国使用的德语区域设置为 de_DE
.
验证消息
验证消息硬编码在它们各自的约束类中.
翻译验证消息
Symfony 使用 Twig 来呈现所有验证消息.这个过程本身很复杂,超出了这个问题的范围,但重要的部分是每个约束消息都是通过一个翻译过滤器发送的,它取决于用户的语言环境(默认为default_locale
)翻译以正确的语言发送消息.
要更改任何翻译,只需将验证翻译文件从 vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Resources/translations/validators.{lang}.xlf
复制到 app/Resources/translations/validators.{lang}.xlf
其中 {lang}
是默认语言环境的语言部分.
完成前者后,只需将默认消息更改为您认为更合适的消息即可.如果您需要支持的语言不存在,请将任何翻译文件复制到同一目录并修改该文件.
要了解有关 Symfony2 中翻译工作原理的更多信息,请访问关于翻译的官方文档.>
When you use @Assert\NotBlank
constraint and the given field is empty, then you get the error:
I would like to change this message application-wide, without changing Symfony2 source code. How to accomplish that?
Cutomizing validation error messages is quite simple, but can seem tricky at first.
Default locale
First of all you should change the default locale of your application. In versions 2.0.x the correct value to change is framework.session.default_locale
. For future reference, starting from 2.1.0 it'll be framework.default_locale
. Consult the docs for correct syntax.
A locale should consist of your language and region and is defined as language_REGION
(list of languages, list of countries). The locale used in Germany for german would be de_DE
for example.
Validation messages
Validation messages are hard coded in their respective constraint classes.
Translating validation messages
Symfony uses Twig to render all the validation messages. The process itself is complicated and falls out of the scope of this question, but the important part is that each constraint message is sent through a translation filter, which depending on the user's locale (default_locale
by default) translates the messages to the proper language.
To change any of the translations, simply copy the validation translation file from vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Resources/translations/validators.{lang}.xlf
to app/Resources/translations/validators.{lang}.xlf
where {lang}
is the language part of your default locale.
Having done the former, simply change the default messages to what ever you see more fit. If the language you need support for doesn't exist, copy any translation file to the same directory and modify that file instead.
To read more about how translation works in Symfony2, visit the official documentation on translation.
这篇关于如何在 Symfony2 中自定义/本地化 Assert 消息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!