Symfony 表单错误参数不起作用

Symfony3 Form-Error Parameters not working

我在使用 Symfony 3 表单错误组件时遇到问题。我需要在表单中添加我自己的错误,但参数没有被值替换。

$form->get('price')->addError(
    new \Symfony\Component\Form\FormError("Maximal value is %price% %currency%.", 
    null, 
    array('%price%' => 100, '%currency%' => 'YPI')));

我尝试像在其他验证器中一样使用 {{ currency }}{{ price }} 的参数,但仍然无效。

有这种方法:http://quedig.com/questions/35271649/symfony-form-error-message-parameters-usage/但这不是最好的方法 - 我仍然相信更好的解决方案,我可以使用经典翻译,而无需将翻译服务的结果放在这里。

FormError 的最佳用法是什么? Symfony3手册无语

谢谢。

传递给 FormError 的构造函数的消息必须已经翻译。否则,它们将按原样显示。所以你的代码看起来像这样:

// $translator should be the "translator" service
$message = $translator->trans('Maximal value is %price% %currency%.', [
    '%price%' => 100,
    '%currency%' => 'YPI',
]);
$form->get('price')->addError(new FormError($message));

顺便说一句,我建议使用消息占位符而不是真正的消息作为要翻译的字符串(参见http://symfony.com/doc/current/best_practices/i18n.html#translation-keys