Symfony validation messages always in default locale

So I’ve configured a site to have several locales depending on the locale in the URL, for example:

http://127.0.0.1:8000/signup/es/
http://127.0.0.1:8000/signup/en/

I have a LocaleSubscriber, like this:

public function onKernelRequest(RequestEvent $event)
{
    $request = $event->getRequest();

    /* If first request */
    if (!$request->hasPreviousSession()) {
        /* Set locale in session (locale from URL) */
        // ...
    }

    return;
}

And this works fine for everything except validation messages.
Translations are stored like this:

/translations/messages.en.yaml
/translations/messages.es.yaml
/translations/validators.en.yaml
/translations/validators.es.yaml

The only thing I can see for sure is that whatever I set the default locale to over here:

/config/packages/translation.yaml

For example:

framework:
    default_locale: es
    translator:
        default_path: '%kernel.project_dir%/translations'
        fallbacks:
            - es

Then the validation messages will always be in that locale, in this case ES.
All other translations work fine.
Am I missing something here?
It looks like translations aren’t configured to use the session ‘_locale’ variable or something like this.
Any ideas?

EDIT:
Added route config:

 * @Route(
 *      "/signup/{_locale}/",
 *      locale="en",
 *      requirements={
 *         "_locale": "en|fr|de|es|it"
 *      },
 *      name="signup",
 *      methods={"GET"}
 * )

EDIT:
The kernel request body should look like this for it to work:

if ($locale = $request->attributes->get('_locale')) {
    $request->getSession()->set('_locale', $locale);
} else {
    $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
    }

So the session _locale variable wasn’t updating as expecting on each request.
Thanks guys for helping me troubleshoot it!

Source: Symfony Questions

Was this helpful?

0 / 0

Leave a Reply 0

Your email address will not be published. Required fields are marked *