Warm tip: This article is reproduced from stackoverflow.com, please click
file-upload symfony symfony-forms symfony4 validation

Multiple file validation: "This value should be of type string"

发布于 2020-07-25 22:46:17

I'm trying to use Symfony Validator on a file upload form (form extension's validation) and I'm getting this error message:

messageTemplate: "This value should be of type string." from Symfony\Component\Validator\ConstraintViolation

Upload works well without the validator, and I cant figure out where this message is coming from.

Here's my FormType, with a basic validation as doc's exemple:

    {
        $builder
            ->add('file', FileType::class, [
                'label' => 'Choisir un fichier',
                'mapped' => false,
                'multiple' => true,
                'constraints' => [
                    new File([
                        'maxSize' => '1024k',
                        'mimeTypes' => [
                            'application/pdf',
                            'application/x-pdf',
                        ],
                        'mimeTypesMessage' => 'Please upload a valid PDF document',
                    ])
                ],
            ])
        ;
    }

If I remove maxSize, mimeTypes and/or mimeTypesMessage arguments, I still have the same problem.

I can't use annotations on entity (mapped option is set to false).

Questioner
Cris
Viewed
44
msg 2020-05-04 19:05

The error is due to the File constraint expecting a filename, but since the field has the option multiple is actually receiving an array. To solve it, you have to wrap the constraint in another All constraint, that will apply the inner constraint (File in this case) to each element of the array.

Your code should look like this:

    ->add('file', FileType::class, [
      'label' => 'Choisir un fichier',
      'mapped' => false,
      'multiple' => true,
      'constraints' => [
        new All([
          'constraints' => [
            new File([
              'maxSize' => '1024k',
              'mimeTypesMessage' => 'Please upload a valid PDF document',
              'mimeTypes' => [
                'application/pdf',
                'application/x-pdf'
              ]
            ]),
          ],
        ]),
      ]
    ])