medowlock February 2016

Symfony form error message parameters usage

What is the purpose of the message parameters array in a Symfony form error ?

For example, I have the following case: on a form I have a subscriber in which, based on the information given by the user an API may be called and some additional errors could be added to the Symfony form.

As such, when an error occurs, I add a new error on a field:

$myForm->get('name')->addError(
    new FormError('name.api_invalid', null, array('{{ api_name }}' => $someValue))
);

where 'name.api_invalid' is defined in message.en.yml as

name.api_invalid: "The API says the name is actually {{ api_name }}. Please fix before proceeding."

While the message is translated, the "parameters" are not replaced.

Is this not how form error parameters are supposed to work ?

Note: I can make it work by using

$myForm->get('name')->addError(
    new FormError(
        $this->translator->trans('name.api_invalid', array('{{ api_name }}' => $someValue))
    )
);

but I'm really curious about those error parameters.

Thank you!

Answers


Jason Roman February 2016

The behavior you are looking at was changed in Symfony 2.2:

Translating validation errors is now optional. You can still do so manually if you like, or you can simplify your templates to simply output the already translated message.

If you look at the form_errors block in 2.1 vs. the form_errors block in 2.2 you will see the difference in how the errors are displayed. You could override the block and do it the old way and then import that template wherever you need it, or you can simply translate the error message the way you're doing above (which is how I've typically done it and is perfectly acceptable).

If you're going the route of $translator->trans then I would use %..% in the parameters, as stated in the Symfony documentation:

The placeholders can take on any form as the full message is reconstructed using the PHP strtr function. But the %...% form is recommended, to avoid problems when using Twig.

The {{ }} you are using is more relegated to using Symfony Validators and how they build their violations (example here).

Now, if you want your messages and parameters automatically translated without manually throwing a FormError, then I would s

Post Status

Asked in February 2016
Viewed 1,681 times
Voted 13
Answered 1 times

Search




Leave an answer