I am looking to update some custom module code which updates the file name on upload. In Craft 3 I had this working by listening to the EVENT_AFTER_SAVE
on an Asset. It would detect the ID of the volume it was uploaded to and then change the file name to a random string which then resave the entry to the folder it was saved in.
Since Craft 4 and the changes with filesystems I am no longer able to get back to the volume ID to compare, testing the folder ID does not help as the assets uses a temp folder until the element (User or Entry) has saved.
The volumeId
returns null
within Craft 4, the output shows -_volumeId: null
, sometimes it does have a value against it under certain circumstances.
What is the best way to do this in Craft 4?
I have included the code I was using.
const RENAME_ASSET_VOLUME_FOLDER_IDS = [2,3];
public static function renameAsset($event)
{
$asset = $event->sender;
$isNew = $event->isNew;
// Only update the filename for new assets
if ($isNew) {
// Volume ID
$volumeId = $asset->volumeId;
// Test if asset volume ID is in volume folder array
if (in_array($folderId, self::RENAME_ASSET_VOLUME_FOLDER_IDS)) {
// Get folder
$folder = $asset->getFolder();
// File extension
$extension = $asset->getExtension();
// Generate random string
$randomString = ToolboxHelper::randomString();
// New file name
$newfileName = $randomString . '.' . $extension;
// Update file title
$asset->title = $randomString;
// Save asset
Craft::$app->assets->moveAsset($asset, $folder, $newfileName);
}
}
}