You are here

public function BynderDocumentFormatter::viewElements in Bynder 8.3

Same name and namespace in other branches
  1. 4.0.x src/Plugin/Field/FieldFormatter/BynderDocumentFormatter.php \Drupal\bynder\Plugin\Field\FieldFormatter\BynderDocumentFormatter::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/BynderDocumentFormatter.php, line 78

Class

BynderDocumentFormatter
Plugin implementation of the 'Bynder Document' formatter.

Namespace

Drupal\bynder\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $is_entityreference = $this->fieldDefinition
    ->getType() == 'entity_reference';
  foreach ($items as $delta => $item) {

    /** @var \Drupal\media\MediaInterface $media */
    $media = $is_entityreference ? $item->entity : $items
      ->getEntity();
    if (!$media) {
      continue;
    }
    $source_plugin = $media
      ->getSource();
    if ($source_plugin instanceof Bynder && ($original = $source_plugin
      ->getMetadata($media, 'original'))) {
      if ($this
        ->getSetting('link')) {
        if ($this
          ->getSetting('title_field') && $media
          ->hasField($this
          ->getSetting('title_field')) && !$media
          ->get($this
          ->getSetting('title_field'))
          ->isEmpty()) {
          $title = $media
            ->get($this
            ->getSetting('title_field'))->value;
        }
        else {
          $title = basename($original);
        }
        $elements[$delta] = [
          '#type' => 'link',
          '#title' => $title,
          '#url' => Url::fromUri($original),
        ];
      }
      else {
        $elements[$delta] = [
          '#plain_text' => $original,
        ];
      }
    }
  }
  return $elements;
}