1

I would like to rename new assets by PHP, but somehow it does not work. In Craft 3, I suppose it is like;

Event::on(\craft\services\Elements::class, \craft\services\Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event) {
    if ($event->params['isNewAsset']) {
        $asset = $event->params['asset'];
        $folder_id = $asset->folderId;

        if ($folder_id == "22")
        {
            $filename = $asset->filename . "_test";
            craft()->assets->renameFile($asset, $filename);
        }
    }
});

My code is like that, but this message appears;

Upload failed. The error message was: “Getting unknown property: craft\events\ElementEvent::params

Could you help me?

2

You are mixing Craft 2 methods with Craft 3 methods. This will get the the assets extension with $asset->getFilename(true) and add test_ in the beginning of the filename:

Event::on(
    \craft\services\Elements::class,
    \craft\services\Elements::EVENT_AFTER_SAVE_ELEMENT,
    function(Event $event)   {
        $asset = $event->element;
        $folderId = $asset->getFolder();


        if ($event->isNew && $asset instanceof craft\elements\Asset && $folderId == '22') {
            $newName =  'test_' . $asset->getFilename(true);
            Craft::$app->assets->moveAsset($asset, $folderId, $newName);
        }
    }
);
1

Thank you very much, it works almost I would like to.

Actually, the function of getFolder() gets the folder as a string. So I modified the function like this;

Event::on(\craft\services\Elements::class, \craft\services\Elements::EVENT_AFTER_SAVE_ELEMENT, function(Event $event) {
    if ($event->element instanceof \craft\elements\Asset) {
        $asset = $event->element;
        $folder = $asset->getFolder();
        $folderId = $folder->id;

        if ($event->isNew && $folderId == '22') {
            $newName =  'test_' . $folderId . '_' . $asset->getFilename(true);
            Craft::$app->assets->moveAsset($asset, $folder, $newName);
        }
    }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.