You are here

FieldLink.php in (Entity Reference) Field Formatters 8.2

File

src/Plugin/Field/FieldFormatter/FieldLink.php
View source
<?php

namespace Drupal\field_formatter\Plugin\Field\FieldFormatter;

use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Render\Element;

/**
 * Provides the field link formatter.
 *
 * @FieldFormatter(
 *   id = "field_link",
 *   label = @Translation("Field linker"),
 *   field_types = {
 *   },
 * )
 */
class FieldLink extends FieldWrapperBase {

  /**
   * {@inheritdoc}
   */
  public function viewElements(FieldItemListInterface $items, $langcode) {
    $field_output = $this
      ->getFieldOutput($items, $langcode);
    $elements = [];
    foreach (Element::children($field_output) as $key) {
      $languageManager = \Drupal::languageManager();
      $entityUrl = $items
        ->getEntity()
        ->toUrl('canonical', [
        'language' => $languageManager
          ->getLanguage($langcode),
      ]);
      $elements[$key] = [
        '#type' => 'link',
        '#url' => $entityUrl,
        '#title' => $field_output[$key],
      ];
    }
    return $elements;
  }

}

Classes

Namesort descending Description
FieldLink Provides the field link formatter.