formssymfonylocalesymfony-2.8

Symfony2.8 get locale in form types


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.


Solution

  • 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