Symfony2: Backward Uri (Referrer) during switching locale

后端 未结 4 1930
甜味超标
甜味超标 2021-01-01 08:03

I\'d like to implement locale switcher, but it seems with no luck...

The code below doesn\'t work because the (Referrer) contains the old value of locale...

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-01 08:17

    I provide my solution using the approach with

    $request->headers->get('referer');
    

    as suggested by gilden

    /**
     * Your locale changing controller
     */
    public function localeAction($locale)
    {
        $request = $this->get('request');
        $router = $this->get('router');
        $context = $router->getContext();
        $frontControllerName = basename($_SERVER['SCRIPT_FILENAME']);
    
        if($request->hasSession())
        {
            $session = $request->getSession();
            $session->setLocale($locale);
            $context->setParameter('_locale', $locale);
    
            //reconstructs a routing path and gets a routing array called $route_params
            $url = $request->headers->get('referer');
            $urlElements = parse_url($url);
            $routePath = str_replace('/' . $frontControllerName, '', $urlElements['path']); //eliminates the front controller name from the url path
            $route_params = $router->match($routePath);
    
            // Get the route name
            $route = $route_params['_route'];
    
            // Some parameters are not required to be used, filter them
            // by using an array of ignored elements.
            $ignore_params = array('_route' => true, '_controller' => true, '_locale' => true);
            $route_params = array_diff_key($route_params, $ignore_params);
    
            $url = $this->get('router')->generate($route, $route_params);
    
            return $this->redirect($url);
        }
    }
    

提交回复
热议问题