You are here

public function TaxonomyImageTermReferenceImage::viewElements in Taxonomy Image 8

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/TaxonomyImageTermReferenceImage.php, line 97

Class

TaxonomyImageTermReferenceImage
Plugin implementation of the 'taxonomy_image_term_reference_image' formatter.

Namespace

Drupal\taxonomy_image\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  $image_style_setting = $this
    ->getSetting('image_style');
  $image_link_setting = $this
    ->getSetting('image_link');
  $url = NULL;
  foreach ($this
    ->getEntitiesToView($items, $langcode) as $delta => $entity) {

    // Check if the formatter involves a link.
    if ($image_link_setting == 'content') {
      if (!$entity
        ->isNew()) {
        $url = $entity
          ->urlInfo();
      }
    }
    elseif ($image_link_setting == 'file') {
      $link_file = TRUE;
    }
    if (isset($link_file)) {
      $target_id = Term::load($entity
        ->id())
        ->get('taxonomy_image')
        ->getValue()[0]['target_id'];
      if ($target_id) {
        $file = File::load($target_id);
        $image_uri = $file
          ->getFileUri();
        $url = Url::fromUri(file_create_url($image_uri));
      }
    }
    $item = $entity
      ->get('taxonomy_image')
      ->offsetGet($delta);
    $item_attributes = $item->_attributes;
    unset($item->_attributes);

    // @TODO Add #cache invalidation.
    $elements[$delta] = array(
      '#theme' => 'image_formatter',
      '#item' => $item,
      '#item_attributes' => $item_attributes,
      '#image_style' => $image_style_setting,
      '#url' => $url,
    );
  }
  return $elements;
}