You are here

public function FieldViewBuilder::build in Twig Tweak 3.x

Same name and namespace in other branches
  1. 3.1.x src/View/FieldViewBuilder.php \Drupal\twig_tweak\View\FieldViewBuilder::build()

Returns the render array for a single entity field.

Parameters

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

string $field_name: The field name.

string|array $view_mode: (optional) The view mode that should be used to render the field.

string $langcode: (optional) Language code to load translation.

bool $check_access: (optional) Indicates that access check is required.

Return value

array A render array for the field.

File

src/View/FieldViewBuilder.php, line 46

Class

FieldViewBuilder
Field view builder.

Namespace

Drupal\twig_tweak\View

Code

public function build(EntityInterface $entity, string $field_name, $view_mode = 'full', string $langcode = NULL, bool $check_access = TRUE) : array {
  $build = [];
  $entity = $this->entityRepository
    ->getTranslationFromContext($entity, $langcode);
  $access = $check_access ? $entity
    ->access('view', NULL, TRUE) : AccessResult::allowed();
  if ($access
    ->isAllowed()) {
    if (!isset($entity->{$field_name})) {

      // @todo Trigger error here.
      return [];
    }
    $build = $entity->{$field_name}
      ->view($view_mode);
  }
  CacheableMetadata::createFromRenderArray($build)
    ->merge(CacheableMetadata::createFromObject($access))
    ->merge(CacheableMetadata::createFromObject($entity))
    ->applyTo($build);
  return $build;
}