Version 1
[yaffs-website] / web / core / modules / image / src / Plugin / Field / FieldFormatter / ImageFormatterBase.php
1 <?php
2
3 namespace Drupal\image\Plugin\Field\FieldFormatter;
4
5 use Drupal\Core\Field\EntityReferenceFieldItemListInterface;
6 use Drupal\field\FieldConfigInterface;
7 use Drupal\file\Plugin\Field\FieldFormatter\FileFormatterBase;
8
9 /**
10  * Base class for image file formatters.
11  */
12 abstract class ImageFormatterBase extends FileFormatterBase {
13
14   /**
15    * {@inheritdoc}
16    */
17   protected function getEntitiesToView(EntityReferenceFieldItemListInterface $items, $langcode) {
18     // Add the default image if needed.
19     if ($items->isEmpty()) {
20       $default_image = $this->getFieldSetting('default_image');
21       // If we are dealing with a configurable field, look in both
22       // instance-level and field-level settings.
23       if (empty($default_image['uuid']) && $this->fieldDefinition instanceof FieldConfigInterface) {
24         $default_image = $this->fieldDefinition->getFieldStorageDefinition()->getSetting('default_image');
25       }
26       if (!empty($default_image['uuid']) && $file = \Drupal::entityManager()->loadEntityByUuid('file', $default_image['uuid'])) {
27         // Clone the FieldItemList into a runtime-only object for the formatter,
28         // so that the fallback image can be rendered without affecting the
29         // field values in the entity being rendered.
30         $items = clone $items;
31         $items->setValue([
32           'target_id' => $file->id(),
33           'alt' => $default_image['alt'],
34           'title' => $default_image['title'],
35           'width' => $default_image['width'],
36           'height' => $default_image['height'],
37           'entity' => $file,
38           '_loaded' => TRUE,
39           '_is_default' => TRUE,
40         ]);
41         $file->_referringItem = $items[0];
42       }
43     }
44
45     return parent::getEntitiesToView($items, $langcode);
46   }
47
48 }