You are here

public function BootstrapCarouselImageFormatter::viewElements in Bootstrap Carousel Image Formatter 8.3

Overrides FormatterInterface::viewElements

See also

\Drupal\Core\Field\FormatterInterface::viewElements()

File

src/Plugin/Field/FieldFormatter/BootstrapCarouselImageFormatter.php, line 196

Class

BootstrapCarouselImageFormatter
Plugin implementation of the 'bootstrap_image_carousel_formatter' formatter.

Namespace

Drupal\bootstrap_carousel_if\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $slides = [];
  $element = [];

  // Build files array.
  $files = $this
    ->getEntitiesToView($items, $langcode);

  // Early opt-out if the field is empty.
  if (empty($files)) {
    return $slides;
  }
  $image_style_setting = $this
    ->getSetting('image_style');

  // Collect cache tags to be added for each item in the field.
  $cache_tags = [];
  if (!empty($image_style_setting)) {
    $image_style = $this->imageStyleStorage
      ->load($image_style_setting);
    $cache_tags = $image_style
      ->getCacheTags();
  }
  foreach ($files as $delta => $file) {
    $cache_tags = Cache::mergeTags($cache_tags, $file
      ->getCacheTags());

    // Extract field item attributes for the theme function.
    $item = $file->_referringItem;
    $item_attributes = $item->_attributes;
    $slides[$delta] = [
      'title' => !empty($items[$delta]) ? $items[$delta]
        ->getValue()['title'] : '',
      'image' => [
        '#theme' => 'image_formatter',
        '#item' => $item,
        '#item_attributes' => $item_attributes,
        '#image_style' => $image_style_setting,
        '#cache' => [
          'tags' => $cache_tags,
        ],
      ],
    ];
  }

  // Build theme array.
  $element[0] = [
    '#theme' => 'bootstrap_carousel',
    '#slides' => $slides,
    '#interval' => $this
      ->getSetting('interval'),
    '#pause' => $this
      ->getSetting('pause'),
    '#wrap' => $this
      ->getSetting('wrap'),
    '#indicators' => count($slides) == 1 ? '0' : $this
      ->getSetting('indicators'),
    '#controls' => count($slides) == 1 ? '0' : $this
      ->getSetting('controls'),
  ];
  return $element;
}