Symfony validation on multiple file upload

3.4k views Asked by At

I have a form containing a FileType field. I've set the multiple option to true so the user can upload multiple files at the same time.

$builder->add('myFile', FileType::class, [
                'label' => 'upload file',
                'multiple' => true,
])

Here is the corresponding property in the Entity connected to this form:

     /**
     * @Assert\NotBlank()
     * @Assert\File(mimeTypes = {"application/pdf", "application/x-pdf", "image/jpeg", "image/png"})
     * @ORM\Column(type="array")
     */
     private $myFile;

When I submit the form I get the error:

UnexpectedTypeException in FileValidator.php line 168:
Expected argument of type "string", "array" given

I added curly braces in front of File assert so it looks like this:

* @Assert\File{}(mimeTypes = {"application/pdf", "application/x-pdf", "image/jpeg", "image/png"})

Now it doesn't complain when submitting the form. but the file type validation is also not checked.

Any idea how to make the file type working for multiple selected files?

1

There are 1 answers

1
Jakub Matczak On

Since you're validating array of File, you need to apply All validator, which will apply inner validators on each element of the array.

Try with something like:

/**
 * @Assert\All({
 *     @Assert\NotBlank(),
 *     @Assert\File(mimeTypes = {"application/pdf", "application/x-pdf", "image/jpeg", "image/png"})
 * })
 * @ORM\Column(type="array")
 */
 private $myFile;