Confidence
Confidence

Reputation: 2303

Symfony2 Forms: Generating checkboxes

currently i have a form, that generates a Drop-Down-Select from my category-entity:

        $builder
            ->add('category', 'entity',
                    array('class' => 'TrackerMembersBundle:Category',
                            'property' => 'title',));

Now i want to generate checkboxes instead, where i can select more than one option...i searched the symfony2 documentation, but could not find an easy way to do it directly from my Entity.Any idea?

Upvotes: 2

Views: 9844

Answers (3)

Florian Klein
Florian Klein

Reputation: 8915

Because EntityType has parent the ChoiceType, you can use any option from the choice type.

In your case, configuring your category field as following would render checkboxes:

$builder
    ->add('category', 'entity', array(
        'class' => 'TrackerMembersBundle:Category',
        'property' => 'title',
        'multiple' => true,
        'expanded' => true,
    )
);

Note the usage of multiple AND expanded in the options.

Upvotes: 10

Seldaek
Seldaek

Reputation: 42026

Adding 'multiple' => true to the option array (the last one where class and property are) gives you a multi-select.

Then you could override the choice_widget block, using form theming.

Something like this might work:

{% block choice_widget %}
{% spaceless %}
    {% for choice, label in choices %}
        <label>
            <input type="checkbox" value="{{ choice }}"{% if _form_is_choice_selected(form, choice) %} selected="selected"{% endif %}>
            {{ label|trans }}
        </label>
    {% endfor %}
{% endspaceless %}
{% endblock choice_widget %}

Upvotes: 11

Chris McKinnel
Chris McKinnel

Reputation: 15082

Try

       $builder
        ->add('category', 'checkbox',
                array('class' => 'TrackerMembersBundle:Category',
                        'property' => 'title',));#

http://symfony.com/doc/current/reference/forms/types/checkbox.html

Upvotes: 0

Related Questions