Symfony2 language selector

前端 未结 5 685
深忆病人
深忆病人 2020-12-24 09:18

I would like to integrate a simple HTML form allowing the user to change Symfony2 web application\'s language (i.e. from page en/faq go to fr/faq). How to do it in a proper

5条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-24 09:45

    You need to call $this->get('session')->setLocale($locale) (replace 'session' by 'request' for Symfony 2.1) inside your controller.

    I've created a form, to which I pass an array of languages:

    add('language', 'choice', array(
                'choices' => $langs,
                'required' => false,
            ));
        }
    
        public function getDefaultOptions(array $options)
        {
            return array(
                'languages' => array('fr_FR', 'en_GB'),
                'csrf_protection' => false,
            );
        }
    
        public function getName()
        {
            return 'my_language';
        }
    }
    

    I submit this form to a separate action in a controller, in which I set the locale and return a redirection to last page:

    get('form.factory')->create(
                new LanguageType(),
                array('language' => $this->get('session')->getLocale()),
                array('languages' => $this->container->getParameter('roger.admin.languages', null))
            );
    
            $request = $this->get('request');
            $form->bindRequest($request);
            $referer = $request->headers->get('referer');
    
            if ($form->isValid()) {
                $locale = $form->get('language')->getData();
                $router = $this->get('router');
    
                // Create URL path to pass it to matcher
                $urlParts = parse_url($referer);
                $basePath = $request->getBaseUrl();
                $path = str_replace($basePath, '', $urlParts['path']);
    
                // Match route and get it's arguments
                $route = $router->match($path);
                $routeAttrs = array_replace($route, array('_locale' => $locale));
                $routeName = $routeAttrs['_route'];
                unset($routeAttrs['_route']);
    
                // Set Locale
                $this->get('session')->setLocale($locale);
    
                return new RedirectResponse($router->generate($routeName, $routeAttrs));
            }
    
            return new RedirectResponse($referer);
        }
    }
    

    Works with any valid locale (you pass them as 'language' option while creating your form), provided that the PHP intl extension is enabled. If it's not, you'll need to replace \Locale::getDisplayName($lang) by a manually created list of locale names.

提交回复
热议问题