Nathalie RUFF
Nathalie RUFF

Reputation: 41

Symfony transform ChoiceType in CheckboxType

I've problem with my form type. I have an entity activity and an other entity class. It's in ManyToMany. When I display the form, it's in ChoiceType, but I want it to be in CheckboxType. So I've :

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('libelle')
        ->add('horraire')
        ->add('horraireDebut')
        ->add('horraireFin')
        ->add('description')
        ->add('classes');
}

It display a ChoiceType but I want a CheckboxType, so I changed this to :

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('libelle')
        ->add('horraire')
        ->add('horraireDebut')
        ->add('horraireFin')
        ->add('description')
        ->add('classes', CheckboxType::class);
}

But this only displays one checkbox while I have several recordings (which appears well with the first code).

My form.html.twig :

<div class="form-group{% if form.classes.vars.errors|length %} has-error{% endif %}">
<label for="{{ form.classes.vars.id }}" class="col-sm-3 control-label no-padding-right required">Classes <span class="red">*</span></label>
<div class="col-sm-9">
    {{ form_widget(form.classes,{'attr': {'class': 'form-control'}}) }}
    {{ form_errors(form.classes) }}
</div>

How can I get a checkbox line or a checkbox dropdown ?

Thanks!

Upvotes: 4

Views: 1112

Answers (2)

Sebastian
Sebastian

Reputation: 250

In order to achieve what you're looking for, you could also try the EntityType with a query builder:

->add('classes', EntityType::class, array(
    'by_reference' => true,
    'multiple' => true,   
    'expanded' => false,   
    'class'    => 'AppBundle\Entity\Class',
    'property' => 'name',
    'query_builder' => function(\Doctrine\ORM\EntityRepository $er) {
            $qb = $er->createQueryBuilder('c');
            return $qb->orderBy('c.name', 'ASC');
         }
    ))

Upvotes: 0

yceruto
yceruto

Reputation: 9585

Just use multiple and expanded options together to achieve this (Ref):

$builder->add('classes', null, array(
    'multiple' => true,
    'expanded' => true,
));

Then checkboxes will be rendered.

Note that null value mean EntityType::class in case you use Doctrine ORM. Otherwise, use EntityType::class and 'class' => Entity::class option.

Upvotes: 4

Related Questions