-->

Changing locale with symfony 2.1

2019-02-07 05:12发布

问题:

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

回答1:

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 :-)



回答2:

Restore the old behavior as explain in https://github.com/symfony/symfony/blob/master/UPGRADE-2.1.md#httpfoundation-1 And use the piece of code of Carlos Granados.

You can also read my another answer https://stackoverflow.com/a/12952999/520114



回答3:

If you set the locale in the request, this is just used for the current request. The next time that a request is issued, the default_locale will be used. Even if now (2.1) the locale is set in the request instead of the session, "It is also possible to store the locale in the session instead of on a per request basis. If you do this, each subsequent request will have this locale." (from the docs). So, you need to do:

$this->get('session')->set('_locale', $newlang);