YagoQuinoy
YagoQuinoy

Reputation: 133

Symfony forms - Country choice Locale not symfony's default

I'm trying to render a form select with countries. For that purpose, I'm using the form select choice type "country".

http://symfony.com/doc/current/reference/forms/types/country.html

Everything is fine at this point. The problem comes with internationalization. If a user uses a different language, cities are not being translated.

Following the docs, the "country" choice uses "Locale::getDefault()" to guess the locale. But it comes with a wrong locale.

echo \Locale::getDefault(); // echoes en.

$request = $this->get('request');
echo $request->getLocale(); // echoes symfony current user locale. fr_FR.

How can I use the current symfony locale on "country" choice select?

Upvotes: 2

Views: 1021

Answers (1)

YagoQuinoy
YagoQuinoy

Reputation: 133

Following Nikos M. advice, i've created an event listener to override default locale.

namespace Foo\AppBundle\EventListener;

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


/**
 * Event Listener that overrides intl default locale for "country" choice form
 *
 * @author [email protected]
 */
class LocaleListener implements EventSubscriberInterface {

    public function onFilterControllerEvent(FilterControllerEvent $event)
    {
        $request = $event->getRequest();
        $locale = $request->getLocale();

        \Locale::setDefault($locale);
    }

    public static function getSubscribedEvents()
    {
        return array(
            // Before controller load due to BeSimpleI18nRoutingBundle
            KernelEvents::CONTROLLER => array(array('onFilterControllerEvent', 17)),

        );
    }
}

Upvotes: 2

Related Questions