You are here

public function ExtraFieldDisplayFormattedBase::view in Extra Field 8.2

Same name and namespace in other branches
  1. 8 src/Plugin/ExtraFieldDisplayFormattedBase.php \Drupal\extra_field\Plugin\ExtraFieldDisplayFormattedBase::view()

Builds a renderable array for the field.

Parameters

\Drupal\Core\Entity\ContentEntityInterface $entity: The field's host entity.

Return value

array Renderable array.

Overrides ExtraFieldDisplayInterface::view

File

src/Plugin/ExtraFieldDisplayFormattedBase.php, line 45

Class

ExtraFieldDisplayFormattedBase
Base class for Extra field Display plugins with field wrapper output.

Namespace

Drupal\extra_field\Plugin

Code

public function view(ContentEntityInterface $entity) {
  $elements = $this
    ->viewElements($entity);
  if (!empty($elements) && !$this
    ->isEmpty()) {

    // Construct a render array for the extra field elements.
    // @see \Drupal\Core\Field\FormatterBase::view
    $build = [
      '#theme' => 'field',
      '#title' => $this
        ->getLabel(),
      '#label_display' => $this
        ->getLabelDisplay(),
      // Prevent quickedit from editing this field by using a special view
      // mode.
      // @see quickedit_preprocess_field()
      '#view_mode' => '_custom',
      '#language' => $this
        ->getLangcode(),
      '#field_name' => $this
        ->getFieldName(),
      '#field_type' => $this
        ->getFieldType(),
      '#field_translatable' => $this
        ->isTranslatable(),
      '#entity_type' => $entity
        ->getEntityTypeId(),
      '#bundle' => $entity
        ->bundle(),
      '#object' => $entity,
      '#formatter' => $this
        ->getPluginId(),
    ];
    if ($children = Element::children($elements, TRUE)) {
      $build['#is_multiple'] = TRUE;
      $build['#cache'] = !empty($elements['#cache']) ? $elements['#cache'] : [];

      // Without #children the field will not show up.
      $build['#children'] = '';
      foreach ($children as $key) {

        // Only keys in "#items" property are required in
        // template_preprocess_field().
        $build['#items'][$key] = new \stdClass();
        $build[$key] = $elements[$key];
      }
    }
    else {
      $build['#is_multiple'] = FALSE;

      // Only keys in "#items" property are required in
      // template_preprocess_field().
      $build['#items'][] = new \stdClass();
      $build[] = $elements;
    }
  }
  else {
    $build = $elements;
  }
  return $build;
}