You are here

public function LazyLoad::viewElements in Video Embed Field 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldFormatter/LazyLoad.php \Drupal\video_embed_field\Plugin\Field\FieldFormatter\LazyLoad::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/LazyLoad.php, line 101

Class

LazyLoad
Plugin implementation of the thumbnail field formatter.

Namespace

Drupal\video_embed_field\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $element = [];
  $thumbnails = $this->thumbnailFormatter
    ->viewElements($items, $langcode);
  $videos = $this->videoFormatter
    ->viewElements($items, $langcode);
  foreach ($items as $delta => $item) {
    $itemThumb = [
      $thumbnails[$delta],
    ];

    // Add a play button.
    $itemThumb[] = [
      '#type' => 'html_tag',
      '#tag' => 'button',
      '#attributes' => [
        'class' => [
          'video-embed-field-lazy-play',
        ],
      ],
    ];
    $element[$delta] = [
      '#type' => 'container',
      '#attributes' => [
        'data-video-embed-field-lazy' => (string) $this->renderer
          ->render($videos[$delta]),
        'class' => [
          'video-embed-field-lazy',
        ],
      ],
      '#attached' => [
        'library' => [
          'video_embed_field/lazy-load',
        ],
      ],
      // Ensure the cache context from the video formatter which was rendered
      // early still exists in the renderable array for this formatter.
      '#cache' => [
        'contexts' => [
          'user.permissions',
        ],
      ],
      'children' => $itemThumb,
    ];
  }
  return $element;
}