-
-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Description
Hi.
I want to implement an action to change the locale as it is done in many websites. This lead to a problem: After I have set the new locale to the session the user must be relocated to the page he came from. I found a very 'hacky' solution by modifying the referrer (the locale has to be replaced by the new locale) and redirect the user.
But I know that it is not best practice to rely on the referrer as it is said in the comment of fabpot on #2121 (comment)
So the best way would be to save every page request and it's parameters in the session, so we have a referer we can rely on. A solution is already provided here: http://stackoverflow.com/a/7945303
Maybe this would be the way to solve this:
Symfony's Controller class should get a new method: redirectToReferrer($parameters = array())
So that my action could look like that:
public function setLocaleAction($newLocale) {
$this->get('session')->setLocale($newLocale);
return $this->redirectToReferrer(array('_locale' => $newLocale));
}
Here is my 'hacky' way:
public function setLocaleAction($newLocale) {
$request = $this->getRequest();
// get last requested path
$referer = $request->server->get('HTTP_REFERER');
$lastPath = substr($referer, strpos($referer, $request->getBaseUrl()));
$lastPath = str_replace($request->getBaseUrl(), '', $lastPath);
// get last route
$matcher = $this->get('router')->getMatcher();
$parameters = $matcher->match($lastPath);
// set new locale (to session and to the route parameters)
$parameters['_locale'] = $newLocale;
$this->get('session')->setLocale($newLocale);
// default parameters has to be unsetted!
$route = $parameters['_route'];
unset($parameters['_route']);
unset($parameters['_controller']);
return $this->redirect($this->generateUrl($route, $parameters));
}