function EntityReferenceEntityFormatter::viewElements

Same name and namespace in other branches
  1. 11.x core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/EntityReferenceEntityFormatter.php \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceEntityFormatter::viewElements()
  2. 10 core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/EntityReferenceEntityFormatter.php \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceEntityFormatter::viewElements()
  3. 9 core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/EntityReferenceEntityFormatter.php \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceEntityFormatter::viewElements()
  4. 8.9.x core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/EntityReferenceEntityFormatter.php \Drupal\Core\Field\Plugin\Field\FieldFormatter\EntityReferenceEntityFormatter::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

core/lib/Drupal/Core/Field/Plugin/Field/FieldFormatter/EntityReferenceEntityFormatter.php, line 152

Class

EntityReferenceEntityFormatter
Plugin implementation of the 'entity reference rendered entity' formatter.

Namespace

Drupal\Core\Field\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $view_mode = $this->getSetting('view_mode');
  $elements = [];
  foreach ($this->getEntitiesToView($items, $langcode) as $delta => $entity) {
    $view_builder = $this->entityTypeManager
      ->getViewBuilder($entity->getEntityTypeId());
    $elements[$delta] = $view_builder->view($entity, $view_mode, $entity->language()
      ->getId());
    // Add a resource attribute to set the mapping property's value to the
    // entity's URL. Since we don't know what the markup of the entity will
    // be, we shouldn't rely on it for structured data.
    if (!empty($items[$delta]->_attributes) && !$entity->isNew() && $entity->hasLinkTemplate('canonical')) {
      $items[$delta]->_attributes += [
        'resource' => $entity->toUrl()
          ->toString(),
      ];
    }
  }
  return $elements;
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.