Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing locale with symfony 2.1

Having some issue changing the locale on a symfony 2.1 website.

I can't find a way to be able to change the lang without using the _locale on every routes. I know this is against the fundamental rule, but this content will for example not be indexed by engine as it is member only.

Typically, I would like a simple method to be able to change the locale on the request (BC from version 2.1), or on the session, but can't figure out how to do that smoothly. I also would like to avoid the use of a Listener for that.

config.yml file :

framework:
    translator:      { fallback: %locale% }
    session:

routing.yml file :

route_change_lang:
    pattern:   /changelang/{newlang}
    defaults:  { _controller: AcmeCoreBundle:Default:switchLanguage, newlang: en }
    requirements:
        newlang: en|fr|de

Simple action to update the locale of the router :

public function switchLanguageAction($newlang)
{

    $request = $this->getRequest();

    $request->setLocale($newlang);

    $referer_url = $this->get('request')->headers->get('referer');
    if ($referer_url != null) {
        return $this->redirect($referer_url);
    } else {
        return $this->redirect($this->generateUrl('route_home'));
    }
}

What is the problem? I guess it is related to the default_locale set in the main config.yml file, but documentation is not really clear, any help/hint appreciated

like image 713
Jean-Christophe Meillaud Avatar asked Aug 27 '12 17:08

Jean-Christophe Meillaud


1 Answers

I've come across the same problem, since we cant' use locales in our urls (seo-issues). Also we use locales like en_US and those are stored in a config outside the direct framework access. What I did is registering an event listener and hooking into the onKernelRequest event. There I check if locale is set in session, if not, I add it to both, request and session. This way, the framework keeps on behaving like it did before 2.1 If you need more info on how to do this, comment and I'll edit some exaples in here :-)

like image 109
maschmann Avatar answered Nov 15 '22 05:11

maschmann