Rbijker.com
Rbijker.com

Reputation: 3114

Symfony 3.0 - not translating according to setLocale()

In my config.yml if have the following setting

parameters:
        locale: en
framework:
        translator:      { fallbacks: ["%locale%"] }

In my controller I change the locale to French like this:

$request->setLocale('fr')

When I want to translate something in Twig like this{{ 'Something' | trans }} It doesn't show the text in French, even though in my view this {{ dump(app.request.locale) }} gives me fr. So there is something wrong.

Only when I change the locale in my config.yml to fr like this:

parameters:
        locale: fr

then I see the text in French.

Any suggestions?

Upvotes: 0

Views: 1891

Answers (1)

Rbijker.com
Rbijker.com

Reputation: 3114

I ended up creating a localeListener that sets the locale in the session when setting the locale in the controller like this $request->setLocale('fr'). Now my text gets translated in the corresponding locale, but on only after an extra page refresh.

namespace SiteBundle\EventListener;
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;
        }

        // try to see if the locale has been set as a _locale routing parameter
        if ($locale = $request->attributes->get('_locale')) {
            $request->getSession()->set('_locale', $locale);
        } else {
            // if no explicit locale has been set on this request, use one from the session
            $request->setLocale($request->getSession()->get('_locale', $this->defaultLocale));
        }
    }

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

Upvotes: 1

Related Questions