6

Does anybody know how to set the locale in Symfony2.1?

I am trying with:

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

and

$this->get('request')->setLocale('en_US');

but none of those has any effect, the devbar tells me:

Session Attributes: No session attributes

Anyway, it is always the fallback locale that is used, as defined in config.yml

(PS: I am trying to set up the translation system as described here

fkoessler
  • 6,932
  • 11
  • 60
  • 92
  • possible duplicate of [Set locale in Symfony 2.1](http://stackoverflow.com/questions/12951792/set-locale-in-symfony-2-1) – Peter O. Jan 13 '13 at 03:53

4 Answers4

5

Even though the Symfony 2.1 states that you can simply set the locale via the Request or Session objects, I never managed to have it working, setting the locale simply has no effect.

So I ended up using a listener coupled with twig routing to handle the locale/language:

The listener:

namespace FK\MyWebsiteBundle\Listener;

use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class LocaleListener implements EventSubscriberInterface
    {
    private $defaultLocale;

    public function __construct($defaultLocale = 'en')
    {
        $this->defaultLocale = $defaultLocale;
    }

    public function onKernelRequest(GetResponseEvent $event)
    {
        $request = $event->getRequest();
        if (!$request->hasPreviousSession()) {
            return;
        }

        if ($locale = $request->attributes->get('_locale')) {
            $request->getSession()->set('_locale', $locale);
        } else {
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        }
    }

    static public function getSubscribedEvents()
    {
        return array(
            // must be registered before the default Locale listener
            KernelEvents::REQUEST => array(array('onKernelRequest', 17)),
        );
    }
}

Register the listener in service.xml:

<service id="fk.my.listener" class="FK\MyWebsiteBundle\Listener\LocaleListener">
    <argument>%locale%</argument>
    <tag name="kernel.event_subscriber"/>
</service>

The routing must look like:

homepage:
pattern:  /{_locale}
defaults: { _controller: FKMyWebsiteBundle:Default:index, _locale: en }
requirements:
    _locale: en|fr|zh

And handle the routing with:

{% for locale in ['en', 'fr', 'zh'] %}
    <a href="{{ path(app.request.get('_route'), app.request.get('_route_params')|merge({'_locale' : locale})) }}">
{% endfor %}

This way, the locale will automatically be set when you click on a link to change the language.

fkoessler
  • 6,932
  • 11
  • 60
  • 92
  • this looks like a good solution and also from the official documentation: https://github.com/symfony/symfony/blob/master/UPGRADE-2.1.md#httpfoundation-1 and http://symfony.com/doc/2.0/book/routing.html#adding-requirements but this doesn't work (with symfony2.2)! It cannot work, because the locale is checking from the `$request->attributes` bag, which has nothing to do with the session. In which cases the the locale is within the attributes? You have to extract the locale from the route params with `$request->query->get('locale').` – timaschew Apr 11 '13 at 16:28
  • I am trying to set my locale with this solution. In the controller, if i put a `die('lang: '.$request->getLocale());` the correct lang is shown. But once I am in my Twig template, the locale is set to en. Any idea's? – rolandow Jun 24 '13 at 12:25
2

You set the locale in your parameters.yml.

[parameters]
...
    locale            = en

The fallback from your config.yml references %locale% which is the setting from the above parameters.yml file.

If you are trying to set it on-the-fly then this should work:

$this->get('session')->setLocale('en_US');

Test it by printing it out straight after:

print_r($this->get('session')->getLocale());

Edit

In 2.1 the locale is now stored in the request but can still be set in the session. http://symfony.com/doc/2.1/book/translation.html#handling-the-user-s-locale

$this->get('session')->set('_locale', 'en_US');
// setting via request with get and setLocale
$request = $this->getRequest();
$locale = $request->getLocale();
$request->setLocale('en_US');
Mark
  • 1,754
  • 1
  • 12
  • 14
  • setLocale doesn't exists in 2.1 anymore for the Session class.. The locale is supposedly stored in request now – fkoessler Jan 12 '13 at 02:36
  • You are correct that it is handled differently to what I thought, but you can still set the locale in the session in 2.1. See Edit in answer. – Mark Jan 14 '13 at 10:50
1

It's not:

$this->get('request')->setLocale('en_US');

But:

$this->get('request')->getSession()->set('_locale', 'en_US');
Pang
  • 9,564
  • 146
  • 81
  • 122
0

From the symfony cookbook:

"Locale is stored in the Request, which means that it's not "sticky" during a user's request. In this article, you'll learn how to make the locale of a user "sticky" so that once it's set, that same locale will be used for every subsequent request."

http://symfony.com/doc/current/cookbook/session/locale_sticky_session.html

You can notice this when you set the locale and use the symfony profiler (in dev mode) to view the sub requests.