Symfony 2 – Set Default Locale On Form Login #2

A small update/correction out of sequence:

A few weeks ago i described how to hook into the form login process in order to change the user session´s locale.

In the meantime a non backwards compatible code modification has been introduced that outdated this article. From now on (Symfony 2.0.4) the locale and default locale settings are maintained within the request object (and not as used to be in the session).

So, here is a little update – under reserve – because the locale setting´s logic will probably change again in the future.

At first, the new locale maintenance code by using a LocaleListener is still buggy. Specially this issue breaks the whole thing atm: https://github.com/symfony/symfony/issues/2386

A quick workaround is to change the priority of the listener from 255 to let´s say 127. That forces the SessionListener to initialize the session right BEFORE the locale listener, so that $request->hasPreviousSession() has actually the chance to return TRUE.

Change Symfony\Component\HttpKernel\EventListener\LocaleListener, L. 69

KernelEvents::REQUEST => array(array('onEarlyKernelRequest', 255), array('onKernelRequest', -1)),

to

KernelEvents::REQUEST => array(array('onEarlyKernelRequest', 127), array('onKernelRequest', -1)),

Hopefully a patch will be available soon to fix the problem – source code modifications in this way are things YOU MUST NOT DO!

For now and demonstration purposes only, this will fit. After that, it´s easy to modify our previously elaborated source code to fit the new circumstances:

Change our listener from:

class EventListener
{
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
$token = $event->getAuthenticationToken();
$session = $event->getRequest()->getSession();
$session->setLocale($token->getUser()->getLocale());
}
}

into:

class EventListener
{
public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
$token = $event->getAuthenticationToken();
$request = $event->getRequest();
$session = $request->getSession();
$locale = $token->getUser()->getLocale();
$session->set('_locale', $locale);
$request->setLocale($locale);
}
}

I am still not sure if this is the best solution to the problem – hopefully the new implementation will be well documented in the future or changed in a way the produces less WTFs …

Any comments appreciated.

One Reply to “Symfony 2 – Set Default Locale On Form Login #2”

Leave a Reply

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