You are here

public function RelationEndpointFormatter::viewElements in Relation 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

relation_endpoint/src/Plugin/Field/FieldFormatter/RelationEndpointFormatter.php, line 33
Contains \Drupal\relation_endpoint\Plugin\Field\FieldFormatter\RelationEndpointFormatter.

Class

RelationEndpointFormatter
Plugin implementation of the 'link' formatter.

Namespace

Drupal\relation_endpoint\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $rows = [];
  $header = [
    [
      'data' => t('Entity type'),
    ],
    [
      'data' => t('Entity ID'),
    ],
    [
      'data' => t('Label'),
    ],
  ];
  foreach ($items as $item) {
    $t = [
      '@entity_type' => $item->entity_type,
      '@entity_id' => $item->entity_id,
    ];
    try {
      $storage_handler = \Drupal::entityTypeManager()
        ->getStorage($item->entity_type);
      if ($entity = $storage_handler
        ->load($item->entity_id)) {
        $label = $entity
          ->label();
        $label_cell['data'] = [
          '#type' => 'link',
          '#title' => !empty($label) && strlen($label) > 0 ? $label : t('Untitled', $t),
        ] + $entity
          ->toUrl()
          ->toRenderArray();
      }
      else {
        $label_cell = t('Deleted');
      }
    } catch (PluginNotFoundException $e) {
      $label_cell = t($e
        ->getMessage());
    }
    $rows[] = array(
      $item->entity_type,
      $item->entity_id,
      $label_cell,
    );
  }
  return [
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
  ];
}