简体   繁体   中英

Symfony override _locale parameter

I have created a custom LocaleListener:

class LocaleListener implements EventSubscriberInterface
{
    public function onKernelRequest(GetResponseEvent $event)
    {    
        if ($request->getSession()->get("language")) {
            $lang = $request->getSession()->get("language");
        } else {
            $lang = $request->getPreferredLanguage(array("de", "en"));
        }

        $request->getSession()->set('_locale', $lang);
        $request->setLocale($request->getSession()->get('_locale', $lang));
    }

    public static function getSubscribedEvents()
    {
        return array(
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
        );
    }
}

I get the language code from session (if exists) or from browser. Now I would like to correct / manipulate the route. I am using _locale in my router to set the language code ( en or de ). Now I would like override the user's choice.

For example, the language code in the LocaleListener is de . The user does now request the url which _locale = en (example: /en instead of automatically /de ).

How can I force to set the users _locale to my result form the LocaleListener outside of every controller, with a listener or an other solution?

In this case you need to add RedirectResponse

$event->setResponse(new RedirectResponse($request->getBaseUrl().'/'.$locale.'/'.($params ? '?'.http_build_query($params) : '')));

or use JMSI18nRoutingBundle https://github.com/schmittjoh/JMSI18nRoutingBundle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM