I'm trying to rename files uploaded by users on the frontend. Changing the title is working, but I can't rename the file.
Would appreciate some help!
Event::on(
Asset::class,Asset::EVENT_BEFORE_HANDLE_FILE,function (AssetEvent $event) {
if (Craft::$app->request->isSiteRequest) {
$asset = $event->asset;
$now = new DateTime();
$timestamp = $now->getTimestamp();
$newAssetTitle = Craft::$app->getRequest()->getBodyParam('imageTitle');
$newAssetFilename = StringHelper::toKebabCase($newAssetTitle) . '-' . $timestamp . '.' . $asset->getExtension();
$asset->title = $newAssetTitle; // this works
$asset->filename = $newAssetFilename; // this doesn't work
}
}
);
moveAssetto achieve this, which might be worth a try. Something like:Craft::$app->assets->moveAsset($asset, $asset->getFolder(), $newAssetFilename);The docs for moveAsset do suggest it's intended for renaming. – Martin Spain Jan 12 '23 at 12:26Asset is missing its folder ID. I assume that's because it's onEVENT_BEFORE_HANDLE_FILE. I got it working withEVENT_AFTER_SAVEbut then renaming the title broke. – supazu Jan 12 '23 at 12:32