Search code examples
phpsymfonylocale

Symfony locale changed in event listerner but default again in controller


I've been trying to make Symfony use a user's locale for requests without using the locale in URL paths.

I've followed numerous SO answers and this cookbook article got me quite far.

I get the user's language preference on a login event and set it into the session. Then for each request I have this event listener:

<?php
namespace My\UserBundle\EventListener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class LocaleListener implements EventSubscriberInterface
{
    private $defaultLocale;

    public function __construct($defaultLocale = 'fi')
    {
        $this->defaultLocale = $defaultLocale;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if (!$request->hasPreviousSession()) {
            return;
        }

        // try to see if the locale has been set as a _locale routing parameter
        #if ($locale = $request->attributes->get('_locale')) {
        #    $request->getSession()->set('_locale', $locale);
        #} else {
            // if no explicit locale has been set on this request, use one from the session
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        #}
        echo $request->getLocale();
    }

    public static function getSubscribedEvents()
    {
        return array(
            // must be registered before the default Locale listener
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
        );
    }
}

When I echo the locale in the lister I get "sv" which is correct based on the user's preference. But when I echo $this->getRequest()->getLocale(); in a controller it is again "fi" which is what I have as preferred language in my config and elsewhere. The session key _locale is "sv" in the controller.

How would I go about having the request in the controller and twig to correctly be based on session?


Solution

  • the solution here works: Set Locale in Symfony by GET param

    So the service needs to also get injected with the translator service, and then the translator's ->setLocale should be called to set the locale.