Reputation: 369
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
).
Upvotes: 10
Views: 2946
Reputation: 8171
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'
]
]),
],
]),
]
])
Upvotes: 30