MehdiB
MehdiB

Reputation: 906

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?

Upvotes: 4

Views: 3625

Answers (1)

Jakub Matczak
Jakub Matczak

Reputation: 15656

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;

Upvotes: 4

Related Questions