Score:1

How to load a file entity by uuid?

us flag

So I am trying to use the default image for users in a menu block if a custom one does not exist. And for it I am getting the image file uuid:

$default_image = $user->get('user_picture')->getSetting('default_image');

Then loading the file entity:

$file = Drupal::service('entity.repository')->loadEntityByUuid('file', $default_image['uuid']);

This is returning null. What am I doing wrong? And is there a better way to achieve this?

Score:2
ve flag

This might be what you need?

use Drupal\field\Entity\FieldConfig;
use Drupal\image\Entity\ImageStyle;

if (FieldConfig::loadByName('user', 'user', $imageFieldName)
  ->getSetting('default_image')['uuid']) {

  $imageStyle = ImageStyle::load('thumbnail');

  // Load the default image settings.
  $imageGetSettings = FieldConfig::loadByName('user', 'user', $imageFieldName)
    ->getSetting('default_image');

  // Get the default image URI from settings.
  $imageURI = Drupal::service('entity.repository')
    ->loadEntityByUuid('file', $imageGetSettings['uuid'])
    ->getFileUri();

  // Build image style path.
  $imageStyleURL = $imageStyle->buildUrl($imageURI);

  // Set $imageURL.
  $imageURL = file_url_transform_relative($imageStyleURL);
}
Jed_BH avatar
us flag
I am getting the uuid but the $imagURI bit is returning a null. Core version is 8.9.14 and I am attempting this in hook_link_alter.
Prestosaurus avatar
ve flag
I tested with `HOOK_link_alter()` in a custom module and do see the`$imageURL` of the default image set on a user image field, e.g. `/admin/config/people/accounts/fields`. Can you confirm if you see the `URI` with `kint($imageURI)`?
Jed_BH avatar
us flag
It turned out to be something else. For some reason even though the code returned a uuid there wasn't a file shown as default in the interface. I uploaded a new file and it got working.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.