3

Currently im using the following code to retrieve the uri of an image field:

$field = $paragraph->field_background_image_left;
$uri = $field->entity->getFileUri();

This seems to work fine when the field contains a value. But when no value is set, '$field->entity' will contain null, even when a default image was set for this field.

How do I retrieve the uri of the default image from my field?

2

The default image is stored in field configuration. You can retrieve it as follows:

<?php

use Drupal\field\Entity\FieldConfig;

$field_info = FieldConfig::loadByName('node', 'article', 'field_image');
$image_uuid = $field_info->getSetting('default_image')['uuid'];
$image = Drupal::service('entity.repository')->loadEntityByUuid('file', $image_uuid);
$image_uri = $image->getFileUri();
1

Note that you're probably asking the wrong question, and shouldn't be doing this (more on this below). But if you insist:

Remember that there are two layers of defaults. First the default file as set on the field storage, which can be overridden by the default file as set on the field config.

<?php

use Drupal\Core\Image\Image;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\file\Entity\File;

/* var $file File */
$file = $node->field_hero_image->entity;
if (!$file) {
  /* var $field_config FieldConfig */
  $field_config = FieldConfig::loadByName('node', $node->bundle(), 'field_hero_image');
  $file_uuid = $field_config->getSetting('default_image')['uuid'];
  if (!$file_uuid) {
    /* var $field_storage_config FieldStorageConfig */
    $field_storage_config = FieldStorageConfig::loadByName('node', 'field_hero_image');
    $file_uuid = $field_storage_config->getSetting('default_image')['uuid'];

  }
  $file = \Drupal::service('entity.repository')->loadEntityByUuid('file', $file_uuid);
}
/* var $image Image */
$image = \Drupal::service('image.factory')->get($file->getFileUri());

But this is really only useful if you want to build everything manually. Most of the time it's better/easier just to use the field's ->view( method:

<?php
$build['headshot'] = $node->field_person_headshot->view([
  'label' => 'hidden',
  'type' => 'responsive_image',
  'settings' => [
    'responsive_image_style' => 'people_headshot',
  ],
]);

Further reading:

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.