How to delete completely documents/images from Drupal 9?

211 views Asked by At

im trying to completely delete pdf files from Drupal 9. Basically i need to keep the same url(external url, images are save on S3) path for the documents but we have version changes almost every month. Once i try to remove the file ( even if it says that is not used anywhere) it keeps a record on the files library and is adding _0 _1 when i try to upload with same name.

I have tried https://www.drupal.org/project/file_delete but no luck as it does not delete the file immediately.

2

There are 2 answers

1
hetal chavda On

Use can use Fancy File Delete module https://www.drupal.org/project/fancy_file_delete

What this module can do:

  1. View of all managed files with an option to force delete them via VBO custom actions
  2. Manually deleting managed files by FID (and an option to force the delete if you really want to).
  3. Deleting unused files from the default files directory that are not in the file managed table. AKA deleting all the unmanaged files.
  4. Deleting unused files from the whole install that are no longer attached to nodes & are still in the file usage table. AKA deleting all the orphaned files.
  5. Delete files via drush by fid(s)
2
Balde Binos On

Something like:

<?php

$file_storage = \Drupal::entityTypeManager()->getStorage('file');
$fids = Drupal::entityQuery('file')->condition('status', 1)->execute();
$file_usage = Drupal::service('file.usage');

foreach ($fids as $fid) {

  $file = Drupal\file\Entity\File::load($fid);
  $file_name = $file->getFilename();
  $file_extension = pathinfo($file_name, PATHINFO_EXTENSION)
  $usage = $file_usage->listUsage($file);

  if (count ($usage) == 0 && $file_extension == 'pdf') {

    $file->delete();

  }

}

Be careful as the code relies on Drupal reporting the correct number of nodes where the file is used, and that might not always be the case.

Of course, if some nodes have old revisions pointing to a file, that file will not be reported with usage = 0. The only solution I can come up with, is to delete the old versions before attempting to delete the files.

Something like:

<?php

$type = 'some_type';

$storage = \Drupal::entityTypeManager()->getStorage('node');
$nodes = $storage->loadByProperties(['type' => $type]);

foreach ($nodes as $node) {

    $node_id = $node->id();
    $latest_revision_id = $storage->getLatestRevisionId($node_id);
    $revision_ids = $storage->revisionIds($node);

    foreach ($revision_ids as $revision_id) {

        if ($revision_id != $latest_revision_id) {

            $storage->deleteRevision($revision_id);

            echo 'Revision ' . $revision_id . ' from node id ' . $node_id . ' - deleted.';

        }
        else {

            echo 'Revision ' . $revision_id . ' from node id ' . $node_id . ' - skipped, is the latest.';

        }

        echo PHP_EOL;

    }

}