You are here

public function Render::renderField in Bamboo Twig 8.4

Same name and namespace in other branches
  1. 8.5 bamboo_twig_loader/src/TwigExtension/Render.php \Drupal\bamboo_twig_loader\TwigExtension\Render::renderField()
  2. 8.2 bamboo_twig_loader/src/TwigExtension/Render.php \Drupal\bamboo_twig_loader\TwigExtension\Render::renderField()
  3. 8.3 bamboo_twig_loader/src/TwigExtension/Render.php \Drupal\bamboo_twig_loader\TwigExtension\Render::renderField()

Returns the render array for a single entity field.

Parameters

string $field_name: The field name.

string $entity_type: The entity type.

mixed $id: (optional) The ID of the entity to render.

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

string $formatter: (optional) The formatter that should be used to render the field. Eg. 'text' for textfield or 'url' for linkfield.

Return value

null|array A render array for the field or NULL if the value does not exist.

File

bamboo_twig_loader/src/TwigExtension/Render.php, line 256

Class

Render
Provides some renderer as Twig Extensions.

Namespace

Drupal\bamboo_twig_loader\TwigExtension

Code

public function renderField($field_name, $entity_type, $id = NULL, $langcode = NULL, $formatter = NULL) {
  $entity = $id ? $this
    ->getEntityTypeManager()
    ->getStorage($entity_type)
    ->load($id) : $this
    ->getCurrentRouteMatch()
    ->getParameter($entity_type);

  // Ensure the entity has the requested field.
  if (!$entity
    ->hasField($field_name)) {
    return NULL;
  }

  // Do not continue if the field is empty.
  if ($entity
    ->get($field_name)
    ->isEmpty()) {
    return NULL;
  }
  if ($langcode && $entity
    ->hasTranslation($langcode)) {
    $entity = $entity
      ->getTranslation($langcode);
  }
  $display_options = [
    'label' => 'hidden',
  ];
  if (!is_null($formatter)) {
    $display_options['type'] = $formatter;
  }
  else {

    // We don't have the formatter view display and should fallback on
    // the default formatter.
    $field_type_definition = $this
      ->getFieldTypeManager()
      ->getDefinition($entity
      ->getFieldDefinition($field_name)
      ->getType());
    $display_options['type'] = $field_type_definition['default_formatter'];
  }
  return $entity
    ->get($field_name)
    ->view($display_options);
}