/** The image listener intercepts all events we need: - postLoad: Define the webview, tempFilename and reset the filename for update's events. - prePersist: Upload the image and create an unique filename. - preUpdate: Update the new image and the filename, remove the old one. - preRemove: Remove the image. In the constructor, $assetsHelper, FileUploader $fileUploader, $imageUploadPath are autowired by services.yaml */ assetsHelper = $assetsHelper; $this->fileUploader = $fileUploader; $this->imageUploadPath = $imageUploadPath; } public function postLoad(Image $image, LifecycleEventArgs $args): void { $image->setWebView( $this->assetsHelper->getUrl("/uploads/images/" . $image->getFilename()) ); if (!$image->getTempFilename()) { $image->setTempFilename($image->getFilename()); // Enable update events to be triggered $image->setFilename(null); } } public function prePersist(Image $image, LifecycleEventArgs $args) { $this->image = $args->getEntity(); $filename = $this->fileUploader->upload($this->image->getFile(), $this->imageUploadPath); $this->image->setFilename($filename); } public function preUpdate(Image $image, PreUpdateEventArgs $args) { $this->image = $args->getEntity(); $filename = $this->fileUploader->upload($this->image->getFile(), $this->imageUploadPath); $this->image->setFilename($filename); unlink($this->imageUploadPath . "/" . $this->image->getTempFilename()); } public function preRemove(Image $image, LifecycleEventArgs $args) { $this->image = $args->getEntity(); unlink($this->imageUploadPath . "/" . $this->image->getTempFilename()); } }