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?
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With