Skip to content

Instantly share code, notes, and snippets.

@daggerhart
Created August 16, 2018 03:40
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daggerhart/1cef5d42d01e1eaa6b00ca4874440e82 to your computer and use it in GitHub Desktop.
Save daggerhart/1cef5d42d01e1eaa6b00ca4874440e82 to your computer and use it in GitHub Desktop.
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
Copy link

Excellent, thank you!

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