Making the Locale “Sticky” during a User’s Session

Making the Locale “Sticky” during a User’s Session

Symfony stores the locale setting in the Request, which means that this setting is not automatically saved (“sticky”) across requests. But, you can store the locale in the session, so that it’s used on subsequent requests.

Creating a LocaleSubscriber

Create a new event subscriber. Typically, _locale is used as a routing parameter to signify the locale, though you can determine the correct locale however you want:

  1. // src/EventSubscriber/LocaleSubscriber.php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpKernel\Event\RequestEvent;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. class LocaleSubscriber implements EventSubscriberInterface
  7. {
  8. private $defaultLocale;
  9. public function __construct($defaultLocale = 'en')
  10. {
  11. $this->defaultLocale = $defaultLocale;
  12. }
  13. public function onKernelRequest(RequestEvent $event)
  14. {
  15. $request = $event->getRequest();
  16. if (!$request->hasPreviousSession()) {
  17. return;
  18. }
  19. // try to see if the locale has been set as a _locale routing parameter
  20. if ($locale = $request->attributes->get('_locale')) {
  21. $request->getSession()->set('_locale', $locale);
  22. } else {
  23. // if no explicit locale has been set on this request, use one from the session
  24. $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
  25. }
  26. }
  27. public static function getSubscribedEvents()
  28. {
  29. return [
  30. // must be registered before (i.e. with a higher priority than) the default Locale listener
  31. KernelEvents::REQUEST => [['onKernelRequest', 20]],
  32. ];
  33. }
  34. }

If you’re using the default services.yaml configuration, you’re done! Symfony will automatically know about the event subscriber and call the onKernelRequest method on each request.

To see it working, either set the _locale key on the session manually (e.g. via some “Change Locale” route & controller), or create a route with the _locale default.

Explicitly Configure the Subscriber

You can also explicitly configure it, in order to pass in the default_locale:

  • YAML

    1. # config/services.yaml
    2. services:
    3. # ...
    4. App\EventSubscriber\LocaleSubscriber:
    5. arguments: ['%kernel.default_locale%']
    6. # uncomment the next line if you are not using autoconfigure
    7. # tags: [kernel.event_subscriber]
  • XML

    1. <!-- config/services.xml -->
    2. <?xml version="1.0" encoding="UTF-8" ?>
    3. <container xmlns="http://symfony.com/schema/dic/services"
    4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    5. xsi:schemaLocation="http://symfony.com/schema/dic/services
    6. https://symfony.com/schema/dic/services/services-1.0.xsd">
    7. <services>
    8. <service id="App\EventSubscriber\LocaleSubscriber">
    9. <argument>%kernel.default_locale%</argument>
    10. <!-- uncomment the next line if you are not using autoconfigure -->
    11. <!-- <tag name="kernel.event_subscriber"/> -->
    12. </service>
    13. </services>
    14. </container>
  • PHP

    1. // config/services.php
    2. use App\EventSubscriber\LocaleSubscriber;
    3. $container->register(LocaleSubscriber::class)
    4. ->addArgument('%kernel.default_locale%')
    5. // uncomment the next line if you are not using autoconfigure
    6. // ->addTag('kernel.event_subscriber')
    7. ;

That’s it! Now celebrate by changing the user’s locale and seeing that it’s sticky throughout the request.

Remember, to get the user’s locale, always use the [Request::getLocale](https://github.com/symfony/symfony/blob/4.4/src/Symfony/Component/HttpFoundation/Request.php "Symfony\Component\HttpFoundation\Request::getLocale()") method:

  1. // from a controller...
  2. use Symfony\Component\HttpFoundation\Request;
  3. public function index(Request $request)
  4. {
  5. $locale = $request->getLocale();
  6. }

Setting the Locale Based on the User’s Preferences

You might want to improve this technique even further and define the locale based on the user entity of the logged in user. However, since the LocaleSubscriber is called before the FirewallListener, which is responsible for handling authentication and setting the user token on the TokenStorage, you have no access to the user which is logged in.

Suppose you have a locale property on your User entity and want to use this as the locale for the given user. To accomplish this, you can hook into the login process and update the user’s session with this locale value before they are redirected to their first page.

To do this, you need an event subscriber on the security.interactive_login event:

  1. // src/EventSubscriber/UserLocaleSubscriber.php
  2. namespace App\EventSubscriber;
  3. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  4. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  5. use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
  6. use Symfony\Component\Security\Http\SecurityEvents;
  7. /**
  8. * Stores the locale of the user in the session after the
  9. * login. This can be used by the LocaleSubscriber afterwards.
  10. */
  11. class UserLocaleSubscriber implements EventSubscriberInterface
  12. {
  13. private $session;
  14. public function __construct(SessionInterface $session)
  15. {
  16. $this->session = $session;
  17. }
  18. public function onInteractiveLogin(InteractiveLoginEvent $event)
  19. {
  20. $user = $event->getAuthenticationToken()->getUser();
  21. if (null !== $user->getLocale()) {
  22. $this->session->set('_locale', $user->getLocale());
  23. }
  24. }
  25. public static function getSubscribedEvents()
  26. {
  27. return [
  28. SecurityEvents::INTERACTIVE_LOGIN => 'onInteractiveLogin',
  29. ];
  30. }
  31. }

Caution

In order to update the language immediately after a user has changed their language preferences, you also need to update the session when you change the User entity.

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.