3

How can I get the locale in a typeform?

This is in my controller:

$form = $this->createForm(new ConfiguratorClientType(), $configuratorClient);

I have this in my form builder:

->add('language',
    EntityType::class,
    array(
        'class' => 'CommonBundle:Language',
        'choice_label' => function ($language) {
            return $language->getName()[$locale];
        },
        'attr' => array(
            'class' => 'form-control'
        )
    )
)

but I cant figure out how to get the locale in there.

yceruto
  • 9,230
  • 5
  • 38
  • 65
Keutelvocht
  • 670
  • 2
  • 10
  • 28

2 Answers2

7

If you have installed the intl module, you can use \Locale::getDefault() safely to get the current locale value. Even though the method infers default only, it can be changed through \Locale::setDefault($locale) just what Symfony does in Request::setLocale method.

Therefore, this should work for you:

return $language->getName()[\Locale::getDefault()];

Update:

However, it's not advisable to use this stateful class in your final app. Instead, you should adhere to the Dependency Inversion Principle, injecting the request stack service into your constructor, and retrieving the current locale from there (refer to the other answer for more details), which will be easier to test.

yceruto
  • 9,230
  • 5
  • 38
  • 65
3

You can register your form as a service and inject request stack:

services:
    form:
        class: YourBundle\Form\Type\YourType
        arguments: ["@request_stack"]
        tags:
            - { name: form.type }

and then get locale from your request.

More on request stack http://symfony.com/doc/current/service_container/request.html

or you can pass locale to your formType from your controller:

$locale = $request->getLocale();
$form = $this->createForm(new ConfiguratorClientType($locale), $configuratorClient);

and accept it in construct of your form.

Edit:

Contructor in the formtype:

private $locale = 'en';

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

and then use the locale variable like this in the builder function:

$this->locale
Keutelvocht
  • 670
  • 2
  • 10
  • 28
kunicmarko20
  • 2,095
  • 2
  • 15
  • 25