You are here

public function EntityViewBuilder::viewFieldItem in Drupal 10

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

Builds a renderable array for a single field item.

Parameters

\Drupal\Core\Field\FieldItemInterface $item: FieldItem to be displayed.

string|array $display_options: Can be either the name of a view mode, or an array of display settings. See EntityViewBuilderInterface::viewField() for more information.

Return value

array A renderable array for the field item.

Overrides EntityViewBuilderInterface::viewFieldItem

See also

\Drupal\Core\Entity\EntityViewBuilderInterface::viewField()

File

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

Class

EntityViewBuilder
Base class for entity view builders.

Namespace

Drupal\Core\Entity

Code

public function viewFieldItem(FieldItemInterface $item, $display = []) {
  $entity = $item
    ->getEntity();
  $field_name = $item
    ->getFieldDefinition()
    ->getName();

  // Clone the entity since we are going to modify field values.
  $clone = clone $entity;

  // Push the item as the single value for the field, and defer to viewField()
  // to build the render array for the whole list.
  $clone->{$field_name}
    ->setValue([
    $item
      ->getValue(),
  ]);
  $elements = $this
    ->viewField($clone->{$field_name}, $display);

  // Extract the part of the render array we need.
  $output = $elements[0] ?? [];
  if (isset($elements['#access'])) {
    $output['#access'] = $elements['#access'];
  }
  return $output;
}