How to pre-select a radio station item with Symfony 2?

I am working on a language selection form:

$currentLocale = "en_US"; // This is indeed sent to the formType $langs = array( 'fr_FR' => 'fr', 'en_US' => 'en' ); $builder->add('language', 'language', array( 'choices' => $langs, 'expanded' => true, 'multiple' => false, 'required' => false, 'label' => false, )); 

HTML code looks like this (simplified):

 <div id="languageForm_language"> <input type="radio" value="fr_FR"> <input type="radio" value="en_US"> </div> 

How can I get the second selected item according to the value of $currentLocale ?

+6
source share
2 answers

In your $langs array, you can specify key value pairs, for example:

 array( 0 => 'value1', 1 => 'value2' ) 

Now for example. you want to pre-select value2 , you can set the data attribute on the key from value2 :

 $builder->add('language', 'choice', array( 'choices' => $langs, 'expanded' => true, 'multiple' => false, 'required' => false, 'label' => false, 'data' => 1 )); 

Accordingly, you can set your data attribute to your $currentLocale variable to pre-select it. Your code should look like this:

 $currentLocale = "en_US"; // This is indeed sent to the formType $langs = array( 'fr_FR' => 'fr', 'en_US' => 'en' ); $builder->add('language', 'choice', array( 'choices' => $langs, 'expanded' => true, 'multiple' => false, 'required' => false, 'label' => false, 'data' => $currentLocale )); 

Note: the second parameter from the add() method must be choice not language .

+11
source

If the form is used with a model object, simply set the language on the object itself before passing it to the form:

 $object->setLanguage($currentLocale); $form = $this->createForm('some_form_type', $object); 

Otherwise, set the data parameter to the default language key:

 $builder->add('language', 'language', array( 'choices' => $langs, 'data' => $currentLocale, // ... )); 
+5
source

All Articles