You are here

protected function EntityViewBuilder::getSingleFieldDisplay in Drupal 9

Same name and namespace in other branches
  1. 8 core/lib/Drupal/Core/Entity/EntityViewBuilder.php \Drupal\Core\Entity\EntityViewBuilder::getSingleFieldDisplay()

Gets an EntityViewDisplay for rendering an individual field.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity.

string $field_name: The field name.

string|array $display_options: The display options passed to the viewField() method.

Return value

\Drupal\Core\Entity\Display\EntityViewDisplayInterface

1 call to EntityViewBuilder::getSingleFieldDisplay()
EntityViewBuilder::viewField in core/lib/Drupal/Core/Entity/EntityViewBuilder.php
Builds a renderable array for the value of a single field in an entity.

File

core/lib/Drupal/Core/Entity/EntityViewBuilder.php, line 505

Class

EntityViewBuilder
Base class for entity view builders.

Namespace

Drupal\Core\Entity

Code

protected function getSingleFieldDisplay($entity, $field_name, $display_options) {
  if (is_string($display_options)) {

    // View mode: use the Display configured for the view mode.
    $view_mode = $display_options;
    $display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode);

    // Hide all fields except the current one.
    foreach (array_keys($entity
      ->getFieldDefinitions()) as $name) {
      if ($name != $field_name) {
        $display
          ->removeComponent($name);
      }
    }
  }
  else {

    // Array of custom display options: use a runtime Display for the
    // '_custom' view mode. Persist the displays created, to reduce the number
    // of objects (displays and formatter plugins) created when rendering a
    // series of fields individually for cases such as views tables.
    $entity_type_id = $entity
      ->getEntityTypeId();
    $bundle = $entity
      ->bundle();
    $key = $entity_type_id . ':' . $bundle . ':' . $field_name . ':' . Crypt::hashBase64(serialize($display_options));
    if (!isset($this->singleFieldDisplays[$key])) {
      $this->singleFieldDisplays[$key] = EntityViewDisplay::create([
        'targetEntityType' => $entity_type_id,
        'bundle' => $bundle,
        'status' => TRUE,
      ])
        ->setComponent($field_name, $display_options);
    }
    $display = $this->singleFieldDisplays[$key];
  }
  return $display;
}