How to pre-select a form radio item with Symfony 2?
Solution 1
In your $langs
array you can specify key value pairs like this:
array(
0 => 'value1',
1 => 'value2'
)
Now, e.g. you want to preselect value2
, you can set the data
attribute to the key from value2
:
$builder->add('language', 'choice', array(
'choices' => $langs,
'expanded' => true,
'multiple' => false,
'required' => false,
'label' => false,
'data' => 1
));
According to this, you can set your data
attribute to your $currentLocale
variable to preselect 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 should be choice
not language
.
Solution 2
If the form is used with a model object, just 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
option to the default language key:
$builder->add('language', 'language', array(
'choices' => $langs,
'data' => $currentLocale,
// ...
));
![Yako](https://i.stack.imgur.com/s66dk.jpg?s=256&g=1)
Yako
I'm mainly a UX Designer, user researcher, interface designer. But I also build up some stuff for web and mobile with HTML5, jQuery, PHP, and some pinches of a few frameworks.
Updated on June 11, 2022Comments
-
Yako about 2 years
I'm working on a language choice 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, ));
The HTML code looks like this (simplified):
<div id="languageForm_language"> <input type="radio" value="fr_FR"> <input type="radio" value="en_US"> </div>
How could I get the second item pre-selected, according to the
$currentLocale
value ? -
bpoiss over 11 yearsI just tried it, there was a mistake in the second parameter, 'languante' should be 'choice', because it's a choice field. This code works for me
-
Yako over 11 yearsI understand my code should work. However, it still does not for me... I guess I miss something somewhere...
-
bpoiss over 11 yearsyou changed the second parameter to
choice?
Edited my answer, added the code that works for me -
Yako over 11 yearsThis is precisely what I am looking for. Thanks :)
-
greg over 9 yearsWell, if there are three options in choices i.e. 0,1 and 2 and I preselect with 'data' => 1, then I cannot select 2 anymore BUT I can select 0. It ignores everything bigger than the default. WHY?!