1

I'm building a newsletter subscription form in Symfony2. In this form these is a field where users can select there language. In this example I set it default to NL. But how can I get the active (user selected locate on the platform) locate value and use it here?

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('email', 'text')
        ->add('langId', 'choice', array(
            'translation_domain' => 'messages',
            'choices' => array(
                'NL' => 'dutch',
                'EN' => 'english',
                'DE' => 'german',
            ),
            'data' => 'NL'
        ))
        ->add('save', 'submit');
}
Tom
  • 1,547
  • 7
  • 27
  • 50

1 Answers1

0

In your controller get the locale in a variable. After when creating the form pass as parameter the locale :

$form = $this->createForm(YourType::class, $yourEntity, ['locale' => $locale]);

In your form add in your default options the 'locale' key with null default value :

//from Symfony v2.7
public function configureOptions(OptionsResolver $resolver){
    $resolver->setDefaults(array(
        'locale' => null
    ));
}

//or this for older versions 

public function setDefaultOptions(OptionsResolverInterface $resolver){
    $resolver->setDefaults(array(
        'locale' => null
    );
}

And finally use it to define your default value of your ChoiceType :

'data' => $options['locale'],

Hope this will help you.

Constantin
  • 1,258
  • 10
  • 9