4

Is there a way to delete an entry's assets when the entry is deleted? We're going to end up with a lot of orphaned assets.

Or is this not a feature because an asset can be shared between entries? Thus requiring me to write a plugin to tie into the onDeleteEntry event (Where and how should you listen for entry delete in plugin?)?

2

Or is this not a feature because an asset can be shared between entries?

Bingo.

A plugin is way to go if that's the behavior you're looking for.

5

This is how I did it:

  1. In my custom plugin, in its init function, I use the following statement to hook into the before delete event:

    craft()->on('elements.onBeforeDeleteElements', array($this, 'beforeDeleteElements'));
    
  2. In the same custom plugin, in the beforeDeleteElements function mentioned in step 1, I examine the passed in event, and determine if the entry type being deleted is the entry type I am interested in, if so, I use the following function to find the related assets and then delete them:

    protected function deleteRelatedImages(EntryModel $entry)
    {
        $criteria            = craft()->elements->getCriteria(ElementType::Asset);
        $criteria->relatedTo = $entry;
        $assets              = $criteria->find();
    
        if (!$assets) {
            return;
        }
    
        foreach ($assets as $asset) {
            $sourceType = $asset->getSource()->getSourceType();
            $sourceType->deleteFile($asset);
        }
    }
    

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.