How to pre-select a form radio item with Symfony 2?
Asked Answered
S

2

6

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 ?

Solfeggio answered 28/2, 2013 at 12:2 Comment(1)
Is this form bound to a data object as well, or is it a 'plain' form?Involution
G
12

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.

Garin answered 28/2, 2013 at 12:8 Comment(5)
I 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 meGarin
I understand my code should work. However, it still does not for me... I guess I miss something somewhere...Solfeggio
you changed the second parameter to choice? Edited my answer, added the code that works for meGarin
This is precisely what I am looking for. Thanks :)Solfeggio
Well, 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?!Cloraclorinda
D
5

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,
    // ...
));
Destructible answered 28/2, 2013 at 12:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.