Skip to main content

Drupal 9: How to fix broken - missing files referenced by media image entities

This is a snippet that will search for any broken missing file entities in the media[bundle=image].field_media_image field and set a default value field_media_image.target_id[fid] value for the media image entities.

use Drupal\file\Entity\File;
use Drupal\media\Entity\Media;

function fixBrokenMediaFiles(int $from, int $to) {
  $memory_cache = \Drupal::service('entity.memory_cache');
  //Replace missing image error
  // Local fid = 642
  // Prod fid 190362
  $fid_fix = 190362;
  $file_system = \Drupal::service('file_system');
  $entity = \Drupal::entityTypeManager()->getStorage('media');
  $query = $entity->getQuery();
  $query->condition('bundle', 'image');
  $query->condition('status', 1);
  $query->condition('field_media_image.target_id', [$from, $to], 'BETWEEN');
  $ids = $query->execute();
  $chunks = array_chunk($ids, 100);
  foreach ($chunks as $chunk_ids) {
    foreach ($chunk_ids as $media_id) {
      $media_obj = Media::load($media_id);
      $fid = $media_obj->get('field_media_image')->target_id;
      $file_obj = File::load($fid);
      if ($file_obj) {
        $file_exists_error = $file_system->getDestinationFilename($file_obj->getFileUri(), \Drupal\Core\File\FileSystemInterface::EXISTS_ERROR);
        if ($file_exists_error) {
          print var_dump('media_obj_id: ' . $media_obj->id() . ' fid: ' . $file_obj->id() . ' ' . $file_exists_error);
          $media_obj->set('field_media_image', ['target_id' => $fid_fix]);
          $media_obj->save();
        }
      } else {
        print var_dump('broken fid: ' . $fid . ' at media with id ' . $media_id);
        $media_obj->set('field_media_image', ['target_id' => $fid_fix]);
        $media_obj->save();
      }
    }
    $memory_cache->deleteAll();
  }
}

 

custom module