1

I have an image field that has a default image if no image is uploaded. In mytheme.theme file I am trying to get the default image and display it. Here is the code that I am using:

$field = $entity->get($fieldName); // Loading from field definition
if ($field) {
  $default_image = $field->getSetting('default_image');
  if ($default_image && $default_image['uuid']) {
    $entityrepository = Drupal::service('entity.repository');
    $defaultImageFile = $entityrepository->loadEntityByUuid('file', $default_image['uuid']);
    if ($defaultImageFile) {
      $image_uri = $defaultImageFile->getFileUri();
    }
  }
}

The issue is that the $default_image['uuid'] is empty. I am not sure how that can be if the default image is set. Since the image uuid is empty, the image cannot be loaded and now I am stuck.

What is wrong with the code that I am using? Or is there another way to accomplish this that works?

4
  • Why not use the default image option that comes with the image field? Just edit it and choose the default image. Drupal will render that image for all cases where there is no image provided. Commented Jun 25, 2017 at 22:06
  • @Neograph734 sorry I am not following. Can you provide an example?
    – user5013
    Commented Jun 25, 2017 at 22:11
  • If you go to Structure > Content types > [add/edit a content type] > Manage fields > [Add/Edit image field]. You will see the image field has an option for providing a default image. If your entity is not a piece of content (node) but something else, this page might be elsewhere but it should not affect the functioning of the image field. Commented Jun 25, 2017 at 22:14
  • @Neograph734 - Thanks that did it. Apparently the default image value cannot be set the field level as I had originally set it. Doing it you way worked. Please make your comment an answer so I can award you the credit.
    – user5013
    Commented Jun 25, 2017 at 22:42

1 Answer 1

1

Instead of doing this in code, the Drupal core image fields provide a default image setting in the UI as well.

If you navigate to an image field in the UI (Structure > Content types > [Add/Edit a content type] > Manage fields > [Add/Edit image field]), you can upload a default picture that will be used by Drupal in case no image was provided.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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