简体   繁体   中英

Symfony3 Form-Error Parameters not working

i have problem with using Symfony 3 Form Error component. I need to add my own error to form, but parameters are not replaced with values.

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

I tried use parameters with {{ currency }} and {{ price }} as in other validators but still not works.

There is this way: http://quedig.com/questions/35271649/symfony-form-error-message-parameters-usage/ but it's not the best way - I still believe in better soloutions where i can use classic translations without placing result from translating service here.

What is best usage for FormError? Symfony3 manual is silent.

Thanks.

Messages passed to the constructor of FormError have to be already translated. Otherwise, they will be shown as is. So your code could look something like this:

// $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));

By the way, I suggest to use message placeholders instead of real messages as the string to be translated (see http://symfony.com/doc/current/best_practices/i18n.html#translation-keys )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM