2

How can I get required multiple checkboxes with the EntityType Field instead of a ChoiceType Field in Symfony3? Actually, I'm using:

use Symfony\Bridge\Doctrine\Form\Type\EntityType;

->add('typesAdresses' , EntityType::class , array(
    'class' => 'EKUserBundle:TypeAdresse',
    'required' => true,
    'expanded' => true,
    'multiple' => true,
));

This will output multiple checkboxes but not as required.

In my form it must be required.

baikho
  • 5,203
  • 4
  • 40
  • 47
Sabra
  • 177
  • 2
  • 19

1 Answers1

2

Checkboxes behaviour is different and you might get around it using the choice_attr option:

$builder
    ->add('typesAdresses' , EntityType::class , array(
        'class' => TypeAddresse::class,
        'expanded' => true,
        'multiple' => true,
        'choice_attr' => function($val, $key, $index) {
            return array('required' => true);
        },
    ))
;

However: I assume what you wish to achieve is “at least 1 checkbox checked in a group of checkboxes”. This is a rather different issue on its own and is more thoroughly explained in Using the HTML5 “required” attribute for a group of checkboxes? So you'll probably have to approach this with some JavaScript and leave out the required attributes in your FormType.

baikho
  • 5,203
  • 4
  • 40
  • 47
  • thank for replying me . like you said I want that at least 1 checkbox checked . I tried to fix it without javascript . – Sabra Aug 26 '17 at 14:16