Your Location is: Home > Forms

symfony4 handleRequest not working correctly with fileType in form

From: Kazakstan View: 4994 Keutelvocht 


Im trying to validate my form, it has a fileType field in it. I use asserts to validate the form. The validation works correctly for all field except the fileType field. It is only allowed to upload jpg jpeg and png files, but if I try to upload for example a PDF file it says my form is valid.

This is the code of the field holding the filename in the db

 * @ORM\Column(name="imgHomepage", type="string")
 * @Assert\File(
 *     maxSize = "1024k",
 *     mimeTypes = {"image/jpg", "image/jpeg", "image/png"},
 *     mimeTypesMessage = "Images must be  jpg,  jpeg or  png"
 * )
private $imgHomepage = '';

This is the code of my fileType being added in the formtype of my entity

->add('imgHomepage', FileType::class, [
            'mapped' => false,
            'data_class' => null,
            'required' => false,
            'error_bubbling' => true

This is the code from my controller

$influencer = self::getInfluencerById($influencerId);
$influencerShowForm = self::CreateInfluencerForm($influencer);
if ($influencerShowForm->isSubmitted() && $influencerShowForm->isValid()) {
  // handle form

Best answer

I think its because the field is not mapped, so it does not validate it against the Entity where your Assert annotation is located. Also, that column is a string and your Assert says it must be a file, you should use a different property for the file itself that does not have a column defined (unmapped).

Try setting the constraints option when you add the FileType field in the FormType:

use Symfony\Component\Validator\Constraints as Assert;


->add('imgHomepage', FileType::class, [
            'mapped' => false,
            'data_class' => null,
            'required' => false,
            'error_bubbling' => true,
            'constraints' => new Assert\File([
              'maxSize' => '1024k',
              'mimeTypes' => ["image/jpg", "image/jpeg", "image/png"],
              'mimeTypesMessage' => "Images must be  jpg,  jpeg or  png",