Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreUpdate not triggered

I have this method in my entity:

/**
     * @ORM\PreUpdate()
     * @ORM\PrePersist()
     */
    public function preStore() {
        if ($this->getPictureFile()) {
            $newFilename = sha1(mt_rand());
            $newFilename = $newFilename . '.' . ($this->getPictureFile()->guessExtension());
            $this->setPictureFilename($newFilename);
        }
    }

And when persisting objects everything works just perfectly but on update the method is not triggered at all, i tested it this way:

/**
     * @ORM\PreUpdate()
     * @ORM\PrePersist()
     */
    public function preStore() { var_dump('asdasdasdadsdasdas');
        if ($this->getPictureFile()) {
            $newFilename = sha1(mt_rand());
            $newFilename = $newFilename . '.' . ($this->getPictureFile()->guessExtension());
            $this->setPictureFilename($newFilename);
        }
    }

And in persisting var_dump works, but when I update the object - it doesn't. Why?

like image 855
user2394156 Avatar asked Jun 29 '13 15:06

user2394156


3 Answers

A update does only occur if a entity field (watched from doctrine) gets changed and so on the preupdate method is only called after a change.

Caution: i guess your picture file is not a doctrine column and so on not watched by doctrine. So your entity does not change for doctrine.

From How to handle File Uploads with Doctrine cookbook article

The PreUpdate and PostUpdate callbacks are only triggered if there is a change in one of the entity's field that are persisted. This means that, by default, if you modify only the $file property, these events will not be triggered, as the property itself is not directly persisted via Doctrine. One solution would be to use an updated field that's persisted to Doctrine, and to modify it manually when changing the file.

EDIT: Or you use the Uploadable behavior of the doctrine extensions

like image 158
Emii Khaos Avatar answered Nov 05 '22 01:11

Emii Khaos


You have to tell doctrine explicitly that your entity has lifecycle-callbacks:

/**
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class YourClass

further you don't need the trailing () in your annotations if you don't prvovide any options.

/**
 * @ORM\PrePersist
 * @ORM\PreUpdate
 */
public function preStore()

consider using a listener/subscriber instead of lifecycle-callbacks allowing easier re-use and keeping your entity cleaner.

More information can be found in the cookbook chapter How to Register Event Listeners and Subscribers.

like image 33
Nicolai Fröhlich Avatar answered Nov 05 '22 00:11

Nicolai Fröhlich


I ran into the same issue, here is my solution:

add a mapped field updatedAt and just call setUpdatedAt(new \DateTime()) inside of the setter of your UploadedFile this will trigger the preUpdate-Event for the entity

like image 32
Nickolaus Avatar answered Nov 05 '22 00:11

Nickolaus