Search code examples
phpsymfonylocale

change locale symfony 2.3


I just began with symfony I'm trying to build a multilang website but I have a problem to change the locale

I read some posts and I read the documentation about this but the locale don't change, I try:

public function indexAction()
{    
    $this->get('session')->set('_locale', 'fr');

    $request = $this->getRequest();
    $locale = $request->getLocale();
    return $this->render('PhoneMainBundle:Default:index.html.twig',array('locale'=>$locale));
}

but the value in $locale is always 'en' (my default locale)

I also try

public function indexAction()
{    
    $this->get('session')->set('_locale', 'fr');

    $request = $this->getRequest();
    $request->setLocale('fr');
    $locale = $request->getLocale();

    return $this->render('PhoneMainBundle:Default:index.html.twig',array('locale'=>$locale));
}

In this case $locale is fr but the translations are always from messages.en.yml

I'd like in a first time to detect the user locale using $_SERVER['HTTP_ACCEPT_LANGUAGE'], maybe using a listner on each page actualisation ?

and after I will create a route to change the locale

But I 'd like to find a way to change the locale.

Thanks for your help


Solution

  • Based on this and this answers.

    LanguageListener.php:

    <?php
    
    namespace Acme\UserBundle\EventListener;
    use Symfony\Component\HttpFoundation\Session\Session;
    use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
    use Symfony\Component\HttpKernel\Event\GetResponseEvent;
    use Symfony\Component\HttpKernel\HttpKernelInterface;
    
    class LanguageListener
    {
        private $session;
    
        public function setSession(Session $session)
        {
            $this->session = $session;
        }
    
        public function setLocale(GetResponseEvent $event)
        {
            if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
                return;
            }
    
            $request = $event->getRequest();
            $request->setLocale($request->getPreferredLanguage(array('en', 'de')));
    
        }
    }
    

    services.yml:

    acme.language.kernel_request_listener:
        class: Acme\UserBundle\EventListener\LanguageListener
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: setLocale }
    

    About wrong locale detection in twig, there could be a lot of different causes. Search through the SO, you'll definitely find the answer. Make sure that your '_local' var is defined right, make sure that you put your languages files in the right place, etc. FInally, read again the last version of the documentation: http://symfony.com/doc/current/book/translation.html