You are here

public function FieldValueExtension::getTargetEntity in Twig Field Value 8

Same name and namespace in other branches
  1. 2.0.x src/Twig/Extension/FieldValueExtension.php \Drupal\twig_field_value\Twig\Extension\FieldValueExtension::getTargetEntity()

Twig filter callback: Return the referenced entity.

Suitable for entity_reference fields: Image, File, Taxonomy, etc.

Parameters

array|null $build: Render array of a field.

Return value

\Drupal\Core\Entity\ContentEntityInterface|\Drupal\Core\Entity\ContentEntityInterface[]|null A single target entity or an array of target entities. If no target entity is found, null is returned.

File

src/Twig/Extension/FieldValueExtension.php, line 131

Class

FieldValueExtension
Provides field value filters for Twig templates.

Namespace

Drupal\twig_field_value\Twig\Extension

Code

public function getTargetEntity($build) {
  if (!$this
    ->isFieldRenderArray($build)) {
    return NULL;
  }
  if (!isset($build['#field_name'])) {
    return NULL;
  }
  $parent_key = $this
    ->getParentObjectKey($build);
  if (empty($parent_key)) {
    return NULL;
  }

  // Use the parent object to load the target entity of the field.

  /** @var \Drupal\Core\Entity\ContentEntityInterface $parent */
  $parent = $build[$parent_key];
  $entities = [];

  /** @var \Drupal\Core\Field\FieldItemInterface $field */
  foreach ($parent
    ->get($build['#field_name']) as $item) {
    if (isset($item->entity)) {
      $entities[] = $item->entity;
    }
  }
  return count($entities) > 1 ? $entities : reset($entities);
}