I\'d like to implement locale switcher, but it seems with no luck...
The code below doesn\'t work because the (Referrer) contains the old value of locale...
Let me show you my solution. I've written kernel event listener:
like the following:
namespace Expedio\SimpleBundle\Listener;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
class Kernel {
/**
* @var \Symfony\Component\DependencyInjection\ContainerInterface
*/
private $router;
public function __construct(\Symfony\Component\Routing\Router $router) {
$this->router = $router;
}
public function onKernelRequest(GetResponseEvent $event) {
if ($event->getRequestType() !== \Symfony\Component\HttpKernel\HttpKernel::MASTER_REQUEST) {
return;
}
/** @var \Symfony\Component\HttpFoundation\Request $request */
$request = $event->getRequest();
/** @var \Symfony\Component\HttpFoundation\Session $session */
$session = $request->getSession();
$routeParams = $this->router->match($request->getPathInfo());
$routeName = $routeParams['_route'];
if ($routeName[0] == '_') {
return;
}
unset($routeParams['_route']);
$routeData = array('name' => $routeName, 'params' => $routeParams);
//Skipping duplicates
$thisRoute = $session->get('this_route', array());
if ($thisRoute == $routeData) {
return;
}
$session->set('last_route', $thisRoute);
$session->set('this_route', $routeData);
}
}
It just saves last request route data each time user opens a page. And in controller when user wants to change locale I do this:
/**
* @Route("/setlocale/{locale}", name="set_locale")
* @param string $locale
* @return array
*/
public function setLocaleAction($locale) {
/** @var \Symfony\Component\HttpFoundation\Session $session */
$session = $this->get('session');
$session->setLocale($locale);
$last_route = $session->get('last_route', array('name' => 'index'));
$last_route['params']['_locale'] = $locale;
return ($this->redirect($this->generateUrl($last_route['name'], $last_route['params'])));
}