VichUploader: reupload image on entity update

1.6k Views Asked by At

I have entity Asset with field image

 /**
  * @ORM\Table(name="asset")
  * @ORM\Entity(repositoryClass="AppBundle\Repository\AssetRepository")
  * @Vich\Uploadable
  */
 class Asset
 {

     /**
      * @ORM\Column(name="name", type="string", length=255)
      */
     private $name;

     /**
      * @ORM\ManyToOne(targetEntity="Category", inversedBy="assets")
      * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
      */
     private $category;

     /**
      * @ORM\Column(name="image", type="string", length=255, nullable=true)
      */
     private $image;

     /**
      * @Vich\UploadableField(mapping="assets", fileNameProperty="image")
      * @var File
      */
     protected $imageFile;

I am using VichUploader to upload images to S3 bucket. I created custom namer to create file name. During upload entity is uploaded to folder with category name and is named with entity name

public function name($obj, PropertyMapping $mapping)
{
    $category = $obj->getCategory()->getName();
    $name = $obj->getName();
    $file = $mapping->getFile($obj);

    if ($extension = $this->getExtension($file)) {
        $name = sprintf('%s.%s', $name, $extension);
    }

    return $category.'/'.$name;
}

These my upload configurations

oneup_flysystem:
adapters:
    assets_adapter:
        awss3v3:
            client: app.assets.s3
            bucket: '%assets_bucket%'
            prefix: assets

filesystems:
    assets_fs:
        adapter:    assets_adapter
        mount:      assets_fs

vich_uploader:
     db_driver: orm
     storage:   flysystem

mappings:
    assets:
        delete_on_remove: true
        delete_on_update: true
        uri_prefix:       'https://s3-%assets_region%.amazonaws.com/%assets_bucket%/'
        upload_destination: assets_fs
        namer: app.asset_namer

I have following situation: user changes category of Asset. How file can be re-uploaded to new category folder and update name?

UPDATE

I am using EasyAdminBundle. Which handles create and edit entities. So I didn't create FormType and Controller for Asset entity. Here are configs:

easy_admin:
  entities:
   Asset:
    class: AppBundle\Entity\Asset
    label: 'Assets'
    form:
      fields:
        - name
        - {property: 'category', type: entity, type_options: {expanded: false, multiple: false, class: 'AppBundle:Category', required: true}}
        - {property: 'imageFile', type: 'vich_image' }
1

There are 1 best solutions below

0
On

One solution would be to update the Asset::setCategory method logic, to create a new File object when the category name is changed, and pass it to Asset::setImageFile to cause VichUploader to run the update process.

use Symfony\Component\HttpFoundation\File\UploadedFile;

/**
 * @ORM\Table(name="asset")
 * @ORM\Entity(repositoryClass="AppBundle\Repository\AssetRepository")
 * @Vich\Uploadable
 */
class Asset
{
     //...

     public function setCategory(Category $category)  
     {
         if ($this->imageFile && $this->category->getName() !== $category->getName()) {
             $this->setImageFile(new UploadedFile(
                 $this->imageFile->getRealPath(),  //physical path to image file
                 $this->image, //current image name
                 null, 
                 null, 
                 null, 
                 true
             ));
         }
         $this->category = $category;

         return $this;
     }

}

One issue is that by default VichUploader does not populate the entity imageFile property.

To ensure Asset::$imageFile is available, without needing to interact with the vich_uploader.storage service, you will need to add inject_on_load: true to your vich_uploader.mappings settings. This will add a listener to the entity to automatically populate the imageFile property with a File object.

#app/config/config.yml

#...

vich_uploader:
    db_driver: orm
    storage: flysystem
    mappings:
        assets:
            delete_on_remove: true
            delete_on_update: true
            uri_prefix: 'https://s3-%assets_region%.amazonaws.com/%assets_bucket%/'
            upload_destination: assets_fs
            namer: app.asset_namer
            inject_on_load: true

The prefered method would be to add the logic to your controller edit action, or adding a custom event subscriber to a Symfony event that monitors the Asset entity. Though I am not aware of how to accomplish this in relation to a category name change in EasyAdminBundle.