I have an event written for Craft 2 which renames files, which are uploaded to certain sources, to have a 35 character random string, plus its original extension.

I am looking to update this for Craft 3, what is the best way to do that?

craft()->on('assets.saveAsset', function(Event $event) {
    if ($event->params['isNewAsset']) {
        $asset = $event->params['asset'];
        $source = $asset->getSource();

        // Rename profile image file names
        if (in_array($source->id, [2,3])) {
            $extension = IOHelper::getExtension($asset->filename);
            $filename = StringHelper::randomString(35, false).'.'.$extension;
            $filename = StringHelper::toLowerCase($filename);

            $title = $asset->generateAttributeLabel(IOHelper::getFileName($filename, false));

            // Rename the actual file on the server
            craft()->assets->renameFile($asset, $filename);

            // Update the asset's filename and title in the database
            $asset->getContent()->title = $title;
            $asset->setAttribute('filename', $filename);


Your Answer

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

Browse other questions tagged or ask your own question.