I'm trying to implement multilingual website. The languages are croatian, english and german. In multilingual website, the url's have to also be in diffrent languages. So, if croatian url is...
www.example.com/hr/o-nama
the english has to be...
www.example.com/en/about-us
As far as I know, Symfony doesn't have a component that does this. But that is not the problem here. I've managed to solve that problem with object that stores current and previous locale (en
or hr
or de
) so when the locale changes, website gets redirected to the route with the corresponding locale. For example, the names for language specific routes are some_bundle_route_en
or some_bundle_route_hr
. So if the current locale is hr
and the locale gets changed, website gets redirected to the some_bundle_route_en
.
This is the code in the Controller Event listener that I'm implementing this system...
$controller = $event->getController();
if ( ! is_array($controller)) {
return;
}
if($session->has('prev-locale')) {
$prevLocale = $session->get('prev-locale');
if($prevLocale != $locale) {
$session->set('prev-locale', $locale);
$redirectUrl = $router->generate($this->generateWantedRoute($this->request->get('_route'), $locale));
$event->setController(function() use ($redirectUrl) {
return new RedirectResponse($redirectUrl);
});
return;
}
}
else {
$session->set('prev-locale', $locale);
}
This is the program flow: (Let's say that current locale is hr
)
- If
prev-locale
is not set, set it to the current locale. - If
prev-locale
is set, check if the locale has changed. - If the locale has been changed, set
prev-locale
to the current locale and redirect tosome_bundle_route_en
.
The problem is that prev-locale
gets changed to en
for no reason at all. I've debugged it very throughly, and the only way that the locale would change if prev-locale
and current locale are not the same.
The first time I load the page, prev-locale
is hr
and the current locale ($locale
) is also hr
. But if I refresh the page again, the prev-locale
get's changed.
Now, the strangest thing is
, if I copy/paste the same code from the event listener to the controller that is currently executing, the code works perfectly. There are no session problem or strange overwrites.
So if you are considering to answer this question, keep in mind that this same code works in controller but not in the event listener.
I know this is a long one, so anyone that tries to answer it has my eternal gratitude.