Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You need to call <code>$this-&gt;get('session')-&gt;setLocale($locale)</code> (replace 'session' by 'request' for Symfony 2.1) inside your controller.</p> <p>I've created a form, to which I pass an array of languages:</p> <pre><code>&lt;?php class LanguageType extends AbstractType { public function buildForm(FormBuilder $builder, array $options) { $langs = $options['languages']; $langs = array_combine($langs, $langs); foreach ($langs as &amp;$lang) { $lang = \Locale::getDisplayName($lang); } $builder-&gt;add('language', 'choice', array( 'choices' =&gt; $langs, 'required' =&gt; false, )); } public function getDefaultOptions(array $options) { return array( 'languages' =&gt; array('fr_FR', 'en_GB'), 'csrf_protection' =&gt; false, ); } public function getName() { return 'my_language'; } } </code></pre> <p>I submit this form to a separate action in a controller, in which I set the locale and return a redirection to last page:</p> <pre><code>&lt;?php class LanguageController extends Controller { public function switchLanguageAction() { $form = $this-&gt;get('form.factory')-&gt;create( new LanguageType(), array('language' =&gt; $this-&gt;get('session')-&gt;getLocale()), array('languages' =&gt; $this-&gt;container-&gt;getParameter('roger.admin.languages', null)) ); $request = $this-&gt;get('request'); $form-&gt;bindRequest($request); $referer = $request-&gt;headers-&gt;get('referer'); if ($form-&gt;isValid()) { $locale = $form-&gt;get('language')-&gt;getData(); $router = $this-&gt;get('router'); // Create URL path to pass it to matcher $urlParts = parse_url($referer); $basePath = $request-&gt;getBaseUrl(); $path = str_replace($basePath, '', $urlParts['path']); // Match route and get it's arguments $route = $router-&gt;match($path); $routeAttrs = array_replace($route, array('_locale' =&gt; $locale)); $routeName = $routeAttrs['_route']; unset($routeAttrs['_route']); // Set Locale $this-&gt;get('session')-&gt;setLocale($locale); return new RedirectResponse($router-&gt;generate($routeName, $routeAttrs)); } return new RedirectResponse($referer); } } </code></pre> <p>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 <code>\Locale::getDisplayName($lang)</code> by a manually created list of locale names.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload