Search code examples
symfonysymfony-formssymfony-validator

How to avoid empty values from checkbox list by using EntityType form type?


I have a form field like this:

$form->add('tags', EntityType:class, array(
    'class' => Tags::class,
    'multiple' => true,
    'expanded' => true,
    'required' => true,
));

This render a nice checkbox list and I need to ensure that at least one option is selected after submiting the form, but even if the required option is true it doesn't work, I tried with NotBlank() and NotNull() constraints, also doesn't work (i.e. the form is valid).

How to avoid empty values from checkbox list by using EntityType form type?


Solution

  • You can use the Count constraint.

    In your entity class:

    /**
     * @Assert\Count(
     *      min = "1",
     *      minMessage = "You must specify at least one tag"
     * )
     */
    protected $tags
    

    Note that you can specify a max parameter and the according message.

    Also, the required option only add required to your field on the client side, it does nothing on the server side.