A language switcher in Symfony 2.4

SmootQ picture SmootQ · Feb 6, 2014 · Viewed 12.4k times · Source

I have an object Language, and I can add, delete and update languages from the admin page.

What I want to do, is to add a language switcher, I put this html/twig code:

 {% for language in languages %}         
      <li><a href="{{ path('evr_footer_switch_language',{'locale': language.code | lower }) }}">{{ language.language | capitalize }} ({{ language.code }})</a></li>
 {% endfor %}

And an action the route for the action is evr_footer_switch_language, the one I used in the switcher above:

 public function switchlanguageAction($locale = 'en') {

        $this->get('session')->set('_locale', $locale);
        $request = $this->getRequest();
       $request->setLocale($locale);
        return $this->redirect($request->headers->get('referer'));
    }

This is the route I defined for the action/controller switchlanguageAction()

evr_footer_switch_language:
    pattern: /language/switch/{locale}
    defaults: { _controller: EvrHomeBundle:Footer:switchlanguage, locale: en }

It seems to me very simple in principle, you click on the link of the language (got from the database), send the code of the language (exemple : 'fr', 'en', 'zh' etc...) to the action as a $locale variable, then set the Locale of the session/request to this value.

The problem is that none of this works, and the language is still 'EN' (default value).

Note According to the requirements of this project, The language can't be mentioned in the URL (like fr/articles, en/articles), but the same URL (/articles/) can show in different languages, this is why I didn't use the pre-defined slug (_locale).

Thanks

Answer

Jovan Perovic picture Jovan Perovic · Feb 7, 2014

While in search for some more details in order to write an answer I stumbled upon this Symfony cookbook entry: Making the Locale "Sticky" during a User's Session

I think that's exactly what you need ;)