Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony validation on multiple file upload

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?

like image 673
MehdiB Avatar asked Sep 14 '25 23:09

MehdiB


1 Answers

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;
like image 84
Jakub Matczak Avatar answered Sep 17 '25 14:09

Jakub Matczak