8

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)
    ;
}

2 Answers 2

11

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
        ])
    ;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nice example but i want to know how can you specify the default selected role? the data is coming from DB and then you need to display the selected value. I know that is a 4 years old question / answer but i am interested
6

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.