You are here

public function AccordionBlockFormatter::viewElements in Accordion Blocks 8

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides EntityReferenceEntityFormatter::viewElements

File

src/Plugin/Field/FieldFormatter/AccordionBlockFormatter.php, line 28
Contains Drupal\accordion_blocks\Plugin\Field\FieldFormatter\AccordionBlockFormatter.

Class

AccordionBlockFormatter
Plugin implementation of the 'accordion_widget_formatter' formatter.

Namespace

Drupal\accordion_blocks\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $view_mode = $this
    ->getSetting('view_mode');
  $elements = array();
  foreach ($this
    ->getEntitiesToView($items, $langcode) as $delta => $entity) {
    $label = $entity
      ->label();

    // Protect ourselves from recursive rendering.
    static $depth = 0;
    $depth++;
    if ($depth > 20) {
      $this->loggerFactory
        ->get('entity')
        ->error('Recursive rendering detected when rendering entity @entity_type @entity_id. Aborting rendering.', array(
        '@entity_type' => $entity
          ->getEntityTypeId(),
        '@entity_id' => $entity
          ->id(),
      ));
      return $elements;
    }
    if ($entity
      ->id()) {
      $view_builder = \Drupal::entityManager()
        ->getViewBuilder($entity
        ->getEntityTypeId());
      $elements[$delta] = $view_builder
        ->view($entity, $view_mode, $entity
        ->language()
        ->getId());
      $items[$delta]->_attributes += array(
        'resource' => $entity
          ->url(),
        'title' => $label,
      );
    }
    else {

      // This is an "auto_create" item.
      $elements[$delta] = array(
        '#markup' => $label,
      );
    }
    $depth = 0;
  }
  return $elements;
}