I would like to translate my website thanks to an link on the right top.
I found out that, since Symfony 2.1, the locale is not stored in the session anymore.
So, I followed this Symfony documentation: Making the Locale "Sticky" during a User's Session
...Bundle/Service/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 }
./app/config/config.yml
framework:
translator: { fallback: en }
And, I add two links to translate my website on the parent twig template, shown below (Symfony2 locale languages whole page event listener).
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>
When I click on one of these links, the parameter _locale is added.
For instance:
satisfaction?_locale=fr
So, the value of the _locale parameter is fr. Consequently, my website should be translated in french.
Nevertheless, that
var_dump($locale)
in the listener is displayed three times:
null
en
null I don't understand why the
_localeparameter is not found when it displaynulland why theen?
With your listener, you will catch all request and subrequest that is not needed. This explain the three times apparition.
Try to add this following code to your onKernelRequest method:
if (HttpKernel::MASTER_REQUEST != $event->getRequestType()) {
return;
}
This will avoid subRequests and possibly resolve your problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With