ValentinH
ValentinH

Reputation: 958

Get new value of entity field after Doctrine flush

I'm trying to resize an image after persisting an entity with Doctrine. In my Entity code, I'm setting a field to a specific value before the flush and the update :

 /**
 * @ORM\PrePersist()
 * @ORM\PreUpdate()
 */
public function preUpload()
{
    if (null !== $this->getFile()) {
        // do whatever you want to generate a unique name
        $filename = sha1(uniqid(mt_rand(), true));
        $this->image = $filename.'.png';
    }
}

So the image field is supposed to be updated. Then in my controller, I'd like to do my resize job:

if ($form->isValid()) 
    {
        $em->persist($activite);
        $em->flush();

        //resize the image
        $img_path = $activite->getImage();
        resizeImage($img_path);
    }

However, at this point in the code, the value of $activite->image is still null. How can I get the new value?

(Everything is saved well in the database.)

Upvotes: 2

Views: 3362

Answers (2)

ValentinH
ValentinH

Reputation: 958

I found my error.

Actually, I was following this tutorial: http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html

and at some point they give this code to set the file:

 public function setFile(UploadedFile $file = null)
{
    $this->file = $file;
    // check if we have an old image path
    if (isset($this->path)) {
        // store the old name to delete after the update
        $this->temp = $this->path;
        $this->path = null;
    } else {
        $this->path = 'initial';
    }
}

And then after the upload, in the first version (with the random filename), they do :

$this->file = null;

But then in the second version, this code is replace by:

$this->setFile(null);

My problem is that I've tried the two versions to finally come back to the first. However, I forgot to change the line to set the file to null and so everytime my path field was reset to null.

Sorry for this absurdity and thanks for your help.

Upvotes: 0

Nicolai Fröhlich
Nicolai Fröhlich

Reputation: 52513

The EntityManager has a refresh() method to update your entity with the latest values from database.

$em->refresh($entity);

Upvotes: 4

Related Questions