I created a controller that sets the security token manually, according to the encrypted GET parameters. I use this to create a remote login URL that will login when the user follows this link.
Now I would like to add a locale setting. When the Lang parameter is provided, it must set the locale. I added this to the controller:
$lang = strtolower($lang); $this->getRequest()->getSession()->set('_locale', $lang); $this->getRequest()->setLocale($lang); $this->container->get('translator')->setLocale($lang);
The _locale variable is set to customize according to the development panel. The language file is not loaded, but returns to the default language.
I read about creating a Listener to achieve this, but it seems to me that this is useful when you want to specify the language in the url. I do not want to add this to my routing, I just want to set the locale when creating the session.
UPDATE:
I went on to simulate an old beheavor solution , as provided by Symfony. However, setting the Locale query does not work. When I repeat this in my Twig template, the values ββare not equal: req lang: {{ app.request.locale }} session: {{ app.session.get('_locale') }} . The LocaleListener, as shown below, works, although I checked this by inserting die() and also setting the language standard of the Translator service, it seems to work.
So, having installed the translator language, I got this job. However, I do not understand why. Should the translation service use the query language? Why do I need to install this manually?
Is the language object in the Request object for anything other than a translation?
<?php namespace Mb\MyBundle\Listener; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class LocaleListener implements EventSubscriberInterface { private $translator; public function __construct($translator) { $this->translator = $translator; } public function onKernelRequest(GetResponseEvent $event) { $request = $event->getRequest(); if (!$request->hasPreviousSession()) { return; } if (strlen( $request->getSession()->get('_locale') )) { $request->setLocale($request->getSession()->get('_locale')); $this->translator->setLocale($request->getSession()->get('_locale')); } } static public function getSubscribedEvents() { return array(
And in my services.yml I have:
mb.locale.listener: class: Mb\MyBundle\Listener\LocaleListener arguments: [@translator] tags:An - { name: kernel.event_subscriber }
If someone can explain to me what is happening here, I would be very happy :-)