Symfony 2 set locale based on user settings stored in DB

I am trying to set the locale based on the current user settings that are stored in the database.

Our User class has getPreferredLanguage, which returns the locale identifier ('en', 'fr_FR', etc.).

I reviewed the following approach:

  • register the locale listener service that subscribes to the KernelEvents :: REQUEST event.
  • This service has access to the security context (via its constructor)
  • this onKernelRequest service is trying to get the user from the security context, get the user preferred language and set it as the request locale.

Unfortunately this does not work. When the onRequestEvent "locale" method is called for the listener, the security context does not have a token. It seems that the context listener is called at a very late stage (with priority 0), and it is impossible to say that my "local" listener starts before the security context.

Does anyone know how to fix this approach or suggest a different one?

+6
source share
1 answer

You might be interested in the locale listener that I posted in this answer: Locating Symfony2: not counting _locale in a session

Edit: if the user changes his language in the profile, this is not a problem. You can connect to the profile editing success event if you use the FOSUserBundle (wizard). Otherwise, in your profile controller if you are using a homemade system. Here is an example for a FOSUserBundle:

<?php namespace Acme\UserBundle\EventListener; use FOS\UserBundle\Event\FormEvent; use FOS\UserBundle\FOSUserEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class ChangeLanguageListener implements EventSubscriberInterface { public static function getSubscribedEvents() { return array( FOSUserEvents::PROFILE_EDIT_SUCCESS => 'onProfileEditSuccess', ); } public function onProfileEditSuccess(FormEvent $event) { $request = $event->getRequest(); $session = $request->getSession(); $form = $event->getForm(); $user = $form->getData(); $lang = $user->getLanguage(); $session->set('_locale', $lang); $request->setLocale($lang); } } 

and in services.yml

 services: acme.change_language: class: Acme\UserBundle\EventListener\ChangeLanguageListener tags: - { name: kernel.event_subscriber } 

for multiple sessions in multiple browsers is not a problem, as each new session requires a new login. Hmm, well, not after changing the language, since only the current session is updated. But you can change the LanguageListener to support this.
And the case if the administrator changes the language should be negligible.

+2
source

Source: https://habr.com/ru/post/945321/


All Articles