Skip to content

Instantly share code, notes, and snippets.

@fyrebase
Created May 11, 2016 10:23
Show Gist options
  • Select an option

  • Save fyrebase/5abcede1b156efa3bb78b97bcf5ab68d to your computer and use it in GitHub Desktop.

Select an option

Save fyrebase/5abcede1b156efa3bb78b97bcf5ab68d to your computer and use it in GitHub Desktop.

Revisions

  1. fyrebase created this gist May 11, 2016.
    26 changes: 26 additions & 0 deletions gist.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    <?php

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

    if (in_array($source->handle, ['myAssetSource'])) {
    $extension = IOHelper::getExtension($asset->filename);
    $filename = StringHelper::randomString(32, 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);
    craft()->assets->storeFile($asset);
    }
    }
    });
    }