Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 918
Keutelvocht Avatar asked Nov 21 '25 09:11

Keutelvocht


1 Answers

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.

like image 125
yceruto Avatar answered Nov 24 '25 05:11

yceruto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!