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 ?
This is the most basic way to specify the choices that should be used by this field. The choices option is an array, where the array key is the item's label and the array value is the item's value: If there are choice values that are not scalar or the stringified representation is not unique Symfony will use incrementing integers as values.
To do this, you can rely on Symfony’s EventDispatcher component system to analyze the data on the object and modify the form based on the Product object’s data. In this article, you’ll learn how to add this level of flexibility to your forms.
You can view the full list of form events via the Symfony\Component\Form\FormEvents class. For better reusability or if there is some heavy logic in your event listener, you can also move the logic for creating the name field to an event subscriber:
The FormEvents::PRE_SET_DATA line actually resolves to the string form.pre_set_data. Symfony\Component\Form\FormEvents serves an organizational purpose. It is a centralized location in which you can find all of the various form events available.
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
.
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,
// ...
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With