Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate multiple check boxes in symfony2 form

Tags:

php

symfony

I want to display checkboxes from a pre-defined array in my Symfony form. User should be able to select more than one but I am not able to do it.

This is my code:

public function buildForm(FormBuilder $builder, array $options)
{
    $roles = array('role1', 'role2', 'role3');
    $builder
        ->add('name')
        ->add('roles', 'checkbox', $roles)
    ;
}
like image 591
Mirage Avatar asked Jul 13 '12 07:07

Mirage


2 Answers

See the choice type reference.

public function buildForm(FormBuilder $builder, array $options)
{
    $roles = ['role1', 'role2', 'role3'];

    $builder
        ->add('name')
        ->add('roles', 'choice', [
            'choices' => $roles,
            'multiple' => true,
            'expanded' => true
        ])
    ;
}
like image 101
Elnur Abdurrakhimov Avatar answered Sep 25 '22 02:09

Elnur Abdurrakhimov


You can use a choice field instead:

public function buildForm(FormBuilder $builder, array $options)
{        
    $roles = array("role1","role2","role3");
    $builder
        ->add('name')
        ->add('roles', 'choice', array(
            'choices' => $roles,
            'multiple' => true,
            'expanded' => true,
        ))    
    ;
}

Look at the documentation to know how you can have a checkbox, a select, or radio buttons with this field type: http://symfony.com/doc/current/reference/forms/types/choice.html#forms-reference-choice-tags

like image 32
AdrienBrault Avatar answered Sep 22 '22 02:09

AdrienBrault