6

I want to find out whether a physical file is managed by Drupal and if it is, then load it.

I'm having trouble with the documentation which keeps displaying "File not found" at crucial moments, but it seemed that this ought to work:

$query = \Drupal::entityQuery('file');
$query->condition('uri', $file_uri);
$entity_ids = $query->execute();
if (count($entity_ids) == 1) {
    $file = \Drupal::entityLoad($entity_ids[0]);
}

However, I get this message:

PHP Fatal error:  Call to undefined method Drupal::entityLoad()

2 Answers 2

10

There is no such method as \Drupal::entityLoad(). Use the static method on the entity type. Assuming "File", you should use:

$file = \Drupal\file\Entity\File::load(reset($entity_ids));

Berdir pointed out in a comment that QueryInterface::execute() returns an array keyed by entity ID or revision ID so reset() is the thing to use to get the first element.

1
  • 1
    $entity_ids[0] is wrong, the key is the id/revision id, 0 won't exist. use reset()
    – Berdir
    Nov 20, 2016 at 21:18
3

To load the entity by ID you can use the following code:

/** @var \Drupal\file\FileInterface|null $file*/
$file = \Drupal::entityTypeManager()
  ->getStorage('file')
  ->load($entityId);

But if you need to load the file entity by the given file URI there is a method called loadByProperties in EntityStorageInterface:

/** @var \Drupal\file\FileInterface[] $files*/
$files = \Drupal::entityTypeManager()
  ->getStorage('file')
  ->loadByProperties(['uri' => $uri]);
if (!empty($files)) {
  $file = reset($files);
}

See Load a file entity by URI

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.