Symfony 4 - How to fix "file not found" constraint violation when updating existing entity?

Viewed 453

I have a Symfony 4.2 app where the user can create and update rental properties, picture included. I have a problem when updating a rental, the form can't pass validation because the pre-loaded file isn't found ("constraint violation : file not found"). The new file is uploaded via an unmapped property, uploadedPicture, so there's no conflict.

I had this problem a while ago while updating other entities, and setting the properties with a new File object worked like a charm. So I reused the same logic, but I'm still getting an error.

Controller :

$pictureFileName = $rental->getPicture();
$rental->setPicture(
       new File($this->getParameter('rental_directory').'/'. $pictureFileName)
       );

$form = $this->createForm(RentalEditType::class, $rental);
$form->handleRequest($request);
if ($form->isSubmitted()) {
      // error happens here I think, but I'll give you my updating logic too
       if ($form->isValid()) {
            $uploadedFile = $rental->getUploadedPicture();

            if($uploadedFile != null) {
                $pictureFileName = $this->generateUniqueFileName().'.'.$uploadedFile ->guessExtension();

                $uploadedFile ->move(
                    $this->getParameter('rental_directory'),
                    $pictureFileName 
                ); 
            } 
            $rental->setPicture($pictureFileName );
        }
        $this->getDoctrine()->getManager()->flush();

Rental.php

/**
     * @ORM\Column(type="string", length=255, nullable=true)
     * @Assert\File(
     *      maxSize = "1M"
     * )
     * 
     */
    private $picture;/

/**
     * @Assert\File(
     *      maxSize = "1M"
     * )
     */
    private $uploadedPicture;

dump($form->getData())

...
-picture: File {#215 ▼
    path: "assets/uploads/rentals" // right path
    filename: "6040e7ca7792be299ce5b72da6339596.jpg" // right filename
    basename: "6040e7ca7792be299ce5b72da6339596.jpg"
    pathname: "assets/uploads/rentals/6040e7ca7792be299ce5b72da6339596.jpg"
    extension: "jpg"
    realPath: "/home/ubuntu/workspace/website/public/assets/uploads/rentals/6040e7ca7792be299ce5b72da6339596.jpg"
    aTime: 2019-06-22 20:58:36
    mTime: 2019-06-22 20:55:57
    cTime: 2019-06-22 20:55:57
    inode: 1070
    size: 724226
    perms: 0100644
    owner: 1000
    group: 1000
    type: "file"
    writable: true
    readable: true
    executable: false
    file: true
    dir: false
    link: false
  }
...

Strange thing is, when I dump form data, the File is found, it gives me a File object and not a string (the path that I registered in the database) which is what I want, but it doesn't seem to work properly since it can't pass validation. The given path seems right too, and the file exists. All the dumps return what should be expected, files, paths... so why am I getting this error and how can I fix it ?

Thanks !

0 Answers
Related