Reputation: 51
I followed this tutorial instructions to make locale changes "sticky'.
And created an action to change the locale with user request.
The LocaleListener class
<?php
namespace AppBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LocaleListener implements EventSubscriberInterface
{
private $defaultLocale;
public function __construct($defaultLocale = 'en')
{
$this->defaultLocale = $defaultLocale;
}
public function onKernelRequest(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->hasPreviousSession()) {
return;
}
// try to see if the locale has been set as a _locale routing parameter
if ($locale = $request->attributes->get('_locale')) {
$request->getSession()->set('_locale', $locale);
} else {
// if no explicit locale has been set on this request, use one from the session
$request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
}
}
public static function getSubscribedEvents()
{
return array(
// must be registered after the default Locale listener
KernelEvents::REQUEST => array(array('onKernelRequest', 15)),
);
}
}
The directory structure:
The service
services:
app.locale_listener:
class: AppBundle\EventListener\LocaleListener
arguments: ['%kernel.default_locale%']
tags:
- { name: kernel.event_subscriber }
The Action
/**
* @Route("/change-locale/{locale}", name="change_locale", defaults={"locale" = "it"})
*/
public function changeLocaleAction(Request $request) {
$request->setLocale('it');
$ref = $request->headers->get('referer');
return $this->redirect($ref);
}
But its not working, and I am not getting any errors. Why might be the problem?
Upvotes: 1
Views: 1318
Reputation: 5881
You are requesting the _locale
attribute in your request listener, but in your route definition the attribute being set is locale
(note the missing leading underscore).
You need to update your route definition accordingly:
/**
* @Route("/change-locale/{_locale}", name="change_locale", defaults={"_locale" = "it"})
*/
public function changeLocaleAction(Request $request)
{
// ...
}
Upvotes: 1