Andrew Fletcher published: 6 June 2021 2 minutes read
I was trying to create something quite simple. How to get image file uri from media entity id or rendered entity.
Or other variations you might have searched:
- How to load existing media programmatically
- How to get image file uri from media entity id
- Call to a member function getFileUri()
- drupal File::load getFileUri
- drupal getFileUri
The steps to achieve this should be something like:
// get the file id $fid = $entity->field_icon->target_id; // Load the image file. $file = File::load($fid); // Get URI of the image file. $file_uri = $file->getFileUri(); // With the URI, generate a url for non-image style background image. $image_path = file_url_transform_relative(file_create_url($file_uri)); // Create the twig variable to be used in the node.html.twig template file as the background image inline style. $variables['background_image_url'] = $image_path;
The above code is correct. However, the for me it was producing the following error
Error: Call to a member function getFileUri() on null
Solution
The solution to the getFileUri() error is as follows:
At the top of your file ensure that you have
use Drupal\file\Entity\File; use Drupal\file\FileInterface;
Then once you have returned the file load File::load($fid) – to do this the first use must exist in the file (use Drupal\file\Entity\File). Then check that the output generated $file is an instance of FileInterface. This can be completed by
if ($file instanceof FileInterface) { //... code ...// }
Hence completing the second use – use Drupal\file\FileInterface
Related articles
Andrew Fletcher
•
22 Apr 2024
Streamlined Drupal 10 Deployment: Best Practices for Stability and Security
Have you ever walked into a situation and marveled at how a site is still operational? Deployments that are riddled with fail-safes piled atop a shaky foundation. The real challenge lies in gradually persuading the team to embrace change to build a stable, robust deployment process aligned with...
Andrew Fletcher
•
21 Apr 2024
This command will help you spot any unusually large directories
The red flag was when I saw the server disk space is showing a site is taking up 57992.5 MB, where locally the site size is showing 957MB. There is something serious happening here and I need to establish the problem quickly. When dealing with a significant discrepancy in site size...
Andrew Fletcher
•
19 Apr 2024
Extending a Contrib Module's Configuration in Drupal 10: A Case Study with Sitewide Alert
Extending the functionality of a contrib module in Drupal can enhance its usefulness without altering the original codebase. This article provides a step-by-step guide on how to add custom configuration options to an existing contrib module, using the sitewide_alert module as an example. We will...