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' }
One solution would be to update the
Asset::setCategorymethod logic, to create a new File object when the category name is changed, and pass it toAsset::setImageFileto cause VichUploader to run the update process.One issue is that by default VichUploader does not populate the entity imageFile property.
To ensure
Asset::$imageFileis available, without needing to interact with thevich_uploader.storageservice, you will need to addinject_on_load: trueto yourvich_uploader.mappingssettings. This will add a listener to the entity to automatically populate the imageFile property with aFileobject.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.