How to Prevent Image Deletion When Using EasyAdmin 3 in Symfony

Learn how to prevent automatic image deletion in EasyAdmin 3 for Symfony by customizing FileUploadType options. This guide shows you how to override default behaviors to preserve your images when records are deleted.

How to Prevent Image Deletion When Using EasyAdmin 3 in Symfony
Photo by Sam Pak / Unsplash

When building content management systems with Symfony's EasyAdmin bundle, you might encounter an unexpected issue: images getting automatically deleted when you remove a database record.

This behavior, while sometimes desirable, can cause problems in many real-world applications where images might be referenced by multiple entities or need to be preserved for archival purposes.

Fortunately, EasyAdmin provides ways to customize this behavior without having to rebuild the entire admin interface from scratch.

Understanding the Default Behavior

By default, EasyAdmin's image handling system will delete image files from your server when their associated database records are removed. This is designed to prevent orphaned files and keep your storage clean, but it's not always what you want, especially in these scenarios:

  • When images are shared between multiple entities
  • When you need to maintain a historical record of deleted content
  • When implementing soft delete functionality
  • When images are used in other parts of your application

Modifying Image Field Configuration

The first step to prevent automatic image deletion is to override the default field type in your CRUD controller.

public function configureFields(string $pageName): iterable
{
    return [
        ImageField::new('image')
            ->setFormType(FileUploadType::class)
    ];
}

This code explicitly sets the form type to FileUploadType, which gives us access to more configuration options for file handling.

Exploring FileUploadType Options

The FileUploadType class in EasyAdmin contains several configuration options that control how files are managed. If you examine the configureOptions method of this class, you'll find these default settings:

$resolver->setDefaults([
   'upload_dir' => $this->projectDir.'/public/uploads/files/',
   'upload_new' => $uploadNew,
   'upload_delete' => $uploadDelete,
   'upload_filename' => $uploadFilename,
   'upload_validate' => $uploadValidate,
   'download_path' => $downloadPath,
   'allow_add' => $allowAdd,
   'allow_delete' => true,
   'data_class' => $dataClass,
   'empty_data' => $emptyData,
   'multiple' => false,
   'required' => false,
   'error_bubbling' => false,
   'allow_file_upload' => true,
]);

Two key options control deletion behavior:

  • upload_delete: A callable function that handles file deletion
  • allow_delete: A boolean that enables or disables the delete option in the interface

Preventing Image Deletion

To prevent EasyAdmin from deleting your images, you need to override these options:

public function configureFields(string $pageName): iterable
{
    return [
        ImageField::new('image')
            ->setFormType(FileUploadType::class)
            ->setFormTypeOption('allow_delete', false)
            ->setFormTypeOption('upload_delete', function(File $file) {})
    ];
}

This implementation makes two important changes:

  1. Sets allow_delete to false, which removes the delete checkbox from the admin interface
  2. Overrides the upload_delete function with an empty callable that does nothing when deletion would normally occur
💡
By providing an empty function for upload_delete, you effectively tell EasyAdmin to skip the file deletion process entirely, preserving your images on the server even when their associated records are removed.

Additional Customization Options

You can further refine this behavior depending on your needs:

Custom Deletion Logic

Instead of completely preventing deletion, you might want to implement custom logic:

->setFormTypeOption('upload_delete', function(File $file) {
    // Add your custom logic here
    // For example, move the file to an archive directory
    $archivePath = 'uploads/archived/';
    if (!file_exists($archivePath)) {
        mkdir($archivePath, 0777, true);
    }
    rename($file->getPathname(), $archivePath . $file->getFilename());
})

Conditional Prevention

You might want to prevent deletion only in certain cases:

->setFormTypeOption('upload_delete', function(File $file) {
    // Check if image is referenced elsewhere
    $isReferenced = $this->imageRepository->isReferenced($file->getFilename());
    
    // Only delete if not referenced
    if (!$isReferenced) {
        unlink($file->getPathname());
    }
})

Conclusion

Customizing EasyAdmin's image deletion behavior gives you greater control over your application's file management. By overriding the default upload_delete function and adjusting the allow_delete option, you can preserve important images even when their database records are removed.

This approach maintains the convenience of EasyAdmin's admin interface while adapting it to your specific requirements for data preservation.

Whether you need to implement a soft delete strategy, maintain historical records, or simply prevent accidental file loss, these simple configuration changes provide an elegant solution without requiring complex custom development.