0

As there is no native config to control the naming of assets I am trying to write a small plugin to do this. Here is what I have;

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

            $asset = $event->params['asset'];

            // Set the filename to a variable, appending the file extension
            // $extension = $asset->getExtension();
            // $filename = strtolower($asset->filename.md5(time()).'.'.$asset->getExtension());
            $filename = strtolower($asset->filename.'.'.$asset->getExtension());

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

            // Set filename attribute and re-save asset
            $asset->setAttribute('filename', $filename);
            craft()->assets->storeFile($asset);
        }
    });

However, this currently results in a duplication of the extension like so; model-rendering-image.jpg.jpg
special-services.jpg.jpg

If I remove this part of the code '.'.$asset->getExtension()) then the asset isn't renamed at all.

Can't seem to get past this hurdle.

Anyone able to shed some light?

Also is there a reason that assets are not renamed to lowercase by default or why this isn't rolled in as a config option?

Brad Bell
  • 67,440
  • 6
  • 73
  • 143
Terry Upton
  • 1,894
  • 10
  • 28

1 Answers1

1

Just tested your code and it worked as you'd expect if you leave off the extra getExtension() call (the filename property already includes the extension).

$filename = strtolower($asset->filename);

If it's not saving for you with that, you've got some other error happening elsewhere.

Brad Bell
  • 67,440
  • 6
  • 73
  • 143