1

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?

1 Answer 1

2

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);
}
3
  • 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.
    – Jed_BH
    Jun 20, 2021 at 17:09
  • 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)? Jun 22, 2021 at 3:51
  • 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.
    – Jed_BH
    Jun 24, 2021 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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