Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony set value checked on a form type choice

Tags:

forms

symfony

I create a form with FormBuilder with Symfony like :

$builder
            ->add('timeBarOpen', 'time', array('label' => 'Ouverture Bar', 'attr' => array('class' => 'form-control')))
            ->add('timeBarClose', 'time', array('label' => 'Fermeture Bar', 'attr' => array('class' => 'form-control')))
            ->add('timeStartHappyHour', 'time', array('label' => 'Début Happy Hour *', 'attr' => array('class' => 'form-control')))
            ->add('timeEndHappyHour', 'time', array('label' => 'Fin Happy Hour *', 'attr' => array('class' => 'form-control')))
            ->add('day', 'choice', [
                'choices' => $days,
                'multiple' => true,
                'expanded' => true,
                'label' => 'Jour(s) *',
            ])
        ;

$days is an array :

$days = array(
            'Monday'    => 'Lundi',
            'Tuesday'   => 'Mardi',
            'Wednesday' => 'Mercredi',
            'Thursday'  => 'Jeudi',
            'Friday'    => 'Vendredi',
            'Saturday'  => 'Samedi',
            'Sunday'    => 'Dimanche',
        );

So, this field type "choice" generates multiple checkboxes and I need them all to be checked by defaut when the form is created.

How can I do that?

like image 244
Clément Andraud Avatar asked Oct 24 '13 15:10

Clément Andraud


2 Answers

You can use the data parameters to specify some default choices, in your case specify an array, and use the keys of your available choices

$builder
    ->add('day', 'choice', [
        'choices' => $days,
        'multiple' => true,
        'expanded' => true,
        'label' => 'Jour(s) *',
        'data' => array_keys($days)
    ])
;
like image 135
Thomas Piard Avatar answered Oct 18 '22 16:10

Thomas Piard


I had a similar problem with a ChoiceType drop-down list, where I wanted to be able to set the selected value, but I couldn't figure out how to do that. I figured it out from @ThomasPiard 's answer. Thank you!

In my example, I set the 'choices', and the 'data' is set to the value of the array (not the key). This is important - since I couldn't figure out why it didn't work at first.

Here's my sample:

->add('pet_type', ChoiceType::class, array( // Select Pet Type.
        'choices' => array(
                'Substitution' => 'sub',
                'Equivalency' => 'equiv',
        ),
        'label' => 'Select Petition Type:',
        'attr' => array(
                'onchange' => 'changedPetType()',
        ),
        'placeholder' => 'Choose an option',
        'data' => 'equiv',
))

Hopefully it will help someone with the same problem.

like image 31
Alvin Bunk Avatar answered Oct 18 '22 16:10

Alvin Bunk