Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Drupal 8 get file or image field uri. Get default value if field is empty.
<?php
use Drupal\file\Entity\File;
/**
* Get the set or default image uri for a file image field (if either exist)
*
* @link https://drupal.stackexchange.com/questions/194176/loading-default-image-from-a-node-field-in-page-html-twig
*
* @param $entity \Drupal\Core\Entity\ContentEntityBase
* @param $fieldName string
* @return null|string
*/
function _get_file_field_uri($entity, $fieldName) {
$image_uri = NULL;
if( $entity->hasField($fieldName) ) {
// Try loading from field values first.
try {
$field = $entity->{$fieldName};
if ($field && $field->target_id) {
$file = File::load($field->target_id);
if ($file) {
$image_uri = $file->getFileUri();
}
}
}
catch (\Exception $e) {
\Drupal::logger('get_image_uri')->notice($e->getMessage(), []);
}
// If a set value above wasn't found, try the default image.
if (is_null($image_uri)) {
try {
$field = $entity->get($fieldName);
if ($field) {
$default_image = $field->getSetting('default_image');
if ($default_image && $default_image['uuid']) {
$entity_repository = Drupal::service('entity.repository');
/** @var $defaultImageFile File */
$defaultImageFile = $entity_repository->loadEntityByUuid('file', $default_image['uuid']);
if ($defaultImageFile) {
$image_uri = $defaultImageFile->getFileUri();
}
}
}
}
catch (\Exception $e) {
\Drupal::logger('get_image_uri')->notice($e->getMessage(), []);
}
}
}
return $image_uri;
}
<?php
$uri = _get_file_field_uri($node, 'field_image');
$absolute_url = file_create_url($uri);
@charlie59

This comment has been minimized.

Copy link

@charlie59 charlie59 commented Jul 14, 2020

Excellent, thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment