-
Notifications
You must be signed in to change notification settings - Fork 519
Description
| Q | A |
|---|---|
| Bundle version | 2.2.0 |
| Symfony version | 6.2.10 |
| PHP version | 8.1.23 |
Support Question
Hi :)
I have the basic configuration so delete_on_update is set to true. But when I upload another image, the old one is not deleted. Using the interactive debugger, this is due to Vich\UploaderBundle\Handler\UploadHandler::hasUploadedFile() :
protected function hasUploadedFile(object $obj, PropertyMapping $mapping): bool
{
$file = $mapping->getFile($obj);
return $file instanceof UploadedFile || $file instanceof ReplacingFile;
}The $file variable is an instance of Symfony\Component\HttpFoundation\File\File so this method always return false.
In my opinion, it is impossible to reach this stage as we will never deal with an UploadedFile here because the file has already been moved and so converted into its File instance (which is reported here but is normally fixed). I have overcome this problem using the custom listener below but I think I have missed somthing with the delete_on_update option.
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Vich\UploaderBundle\Event\Event;
use Vich\UploaderBundle\Event\Events;
use Vich\UploaderBundle\Handler\UploadHandler;
class VichCleanListener
{
public function __construct(
private readonly UploadHandler $handler,
) {
}
#[AsEventListener(Events::PRE_UPLOAD)]
public function preUpload(Event $event): void
{
$this->handler->clean($event->getObject(), 'imageFile');
}
}Here is the relevant part of my entity Article :
#[Vich\UploadableField(mapping: 'xxx.article_image', fileNameProperty: 'imageName', mimeType: 'imageMimeType')]
#[Assert\File(maxSize: '5M', extensions: self::IMAGE_FILE_EXTENSIONS)]
private File|null $imageFile = null;
#[ORM\Column(type: Types::STRING, nullable: true)]
#[Gedmo\Versioned]
private string|null $imageName = null;
#[ORM\Column(type: Types::STRING, nullable: true)]
private string|null $imageMimeType = null;And here is the yaml config :
vich_uploader:
db_driver: 'orm'
storage: 'flysystem'
mappings:
xxx.article_image:
uri_prefix: '/uploads/articles/images'
upload_destination: 'xxx.article_image.storage'
namer: 'Vich\UploaderBundle\Naming\SmartUniqueNamer'