Created
August 16, 2018 03:40
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$uri = _get_file_field_uri($node, 'field_image'); | |
$absolute_url = file_create_url($uri); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Excellent, thank you!