How to set up Symfony2 sticky locale during session

I would like to translate my site from the link on the top right.

I found out that as of Symfony 2.1, the locale is no longer persisted in the session.

So I followed this Symfony documentation: Creating the "Sticky" locale during a user session

... Bundle / Services / LocaleListener.php

class LocaleListener implements EventSubscriberInterface
{
    private $defaultLocale;

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

    public function onKernelRequest(GetResponseEvent $event)
    {

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

        $locale = $request->attributes->get('_locale');
        var_dump($locale);

        if ($locale) {
             $request->getSession()->set('_locale', $locale);
        } else {
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        }
    }

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

      

... Bundle / Resources / config / services.yml

locale_listener:
    class: ..Bundle\Service\LocaleListener
    arguments: ["%kernel.default_locale%"]
    tags:
        - { name: kernel.event_subscriber }   

      

./application/Config/config.yml

framework:
    translator:      { fallback: en }

      

And I will add two links to translate my website into the parent twig template shown below ( Symfony2 language to listen to all pages ).

base.html.twig

<li><a href="{{-
                path(app.request.get('_route'),
                app.request.get('_route_params')|merge({'_locale' : 'fr'}))
            -}}">FR</a></li>
<li><a href="{{-
                path(app.request.get('_route'),
                app.request.get('_route_params')|merge({'_locale' : 'en'}))
            -}}">EN</a></li>

      

Problem and question

When I click on one of these links a parameter is added _locale

.

For example:

satisfaction?_locale=fr

      

So, the parameter value _locale

fr

. Hence my site must be translated into French.

However, that

var_dump($locale)

      

in the listener is displayed three times:

  • zero

  • an

  • null I don't understand why the parameter was _locale

    not found when displayed null

    and why en

    ?

+3


source to share


1 answer


With your listener, you will catch all queries and subqueries that are not needed. This explains the threefold phenomenon.

Try adding the following code to your method onKernelRequest

:



if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
    return;
}

      

This will avoid subRequests and possibly fix your problem.

+2


source







All Articles