You are here

public function MagnificPopup::viewElements in Magnific Popup 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldFormatter/MagnificPopup.php \Drupal\magnific_popup\Plugin\Field\FieldFormatter\MagnificPopup::viewElements()

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/MagnificPopup.php, line 96

Class

MagnificPopup
Magnific Popup field formatter.

Namespace

Drupal\magnific_popup\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $thumb_image_style = $this
    ->getSetting('thumbnail_image_style');
  $popup_image_style = $this
    ->getSetting('popup_image_style');
  $gallery_type = $this
    ->getSetting('gallery_type');
  $files = $this
    ->getEntitiesToView($items, $langcode);
  foreach ($files as $delta => $file) {
    $image_uri = $file
      ->getFileUri();
    $popup_image_path = !empty($popup_image_style) ? ImageStyle::load($popup_image_style)
      ->buildUrl($image_uri) : $image_uri;

    // Depending on the outcome of https://www.drupal.org/node/2622586,
    // Either a class will need to be added to the $url object,
    // Or a custom theme function might be needed to do so.
    // For the time being, 'a' is used as the delegate in magnific-popup.js.
    $url = Url::fromUri(file_create_url($popup_image_path));
    $item = $file->_referringItem;
    $item_attributes = $file->_attributes;
    unset($file->_attributes);
    $item_attributes['class'][] = 'mfp-thumbnail';
    if ($gallery_type === 'first_item' && $delta > 0) {
      $item_attributes['class'][] = 'visually-hidden';
    }
    $elements[$delta] = [
      '#theme' => 'image_formatter',
      '#item' => $item,
      '#item_attributes' => $item_attributes,
      '#image_style' => $thumb_image_style,
      '#url' => $url,
      '#attached' => [
        'library' => [
          'magnific_popup/magnific_popup',
        ],
      ],
    ];
  }
  return $elements;
}