3
votes

I created a EventListener to set the locale based on the user preferences, i set the langage like this in my listener:

$request->setLocale($user->getLanguage());

$request->getSession()->set('_locale',$user->getLanguage());

I tried both..

I register the Listener in the service.yml:

 app.event_listener.locale:
        class: 'AppBundle\EventListener\LocaleListener'
        arguments:
            - '@security.token_storage'
        tags:
            - {name: 'kernel.event_listener', event: 'kernel.request', method: 'onKernelRequest'}

I also tried to add a priority: 17 to the service but it does not change anything...

The listener seems to works, i can get the Locale in my controller with a $request->getLocale()(or session).

But Twig is still in the default language I defined in the config.yml:

parameters:
    locale: fr

I'm pretty lost now, any tips ?

2
can You post services.yml with definition of this listener? - mmmm
@mmmm I add the service.yml code, i tried to change the priority of the service without any success - Xavier
how do you call it in your twig ? - PASTAGA
@DOZ : I do something like : _{{ 'user.list' | trans({}, 'navigation') }} - Xavier
have you add the translation file corresponding to your translation ? (messages.en.yml if you set your local to 'en' for example) - PASTAGA

2 Answers

1
votes

I tried a lot of stuff (change the priority, check if the locale is passed to the front etc...) Finally i forced the translator in my EventListener:

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

    if ($this->tokenStorage->getToken()) {
        $user = $this->tokenStorage->getToken()->getUser();
        if ($user && $user instanceof User) {
            $request->setLocale($user->getLanguage());
        } elseif ($request->query->has('locale')) {
            $request->setLocale($request->query->get('locale'));
        } else {
            $request->setLocale($request->getPreferredLanguage());
        }
    }
    $this->translator->setLocale($request->getLocale());
}

I don't understand why, this should be done in the Symfony translator, but it works...

0
votes

You have to set the locale for the translator to get the right translation in templates.

E.g in controller:

$this->get('translator')->setLocale($user->getLanguage());