You are here

public function ViewsReferenceFieldFormatter::viewElements in Views Reference Field 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldFormatter/ViewsReferenceFieldFormatter.php \Drupal\viewsreference\Plugin\Field\FieldFormatter\ViewsReferenceFieldFormatter::viewElements()

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 FormatterInterface::viewElements

File

src/Plugin/Field/FieldFormatter/ViewsReferenceFieldFormatter.php, line 75

Class

ViewsReferenceFieldFormatter
Field formatter for Viewsreference Field.

Namespace

Drupal\viewsreference\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  foreach ($items as $delta => $item) {
    $view_name = $item
      ->getValue()['target_id'];
    $display_id = $item
      ->getValue()['display_id'];
    $argument = $item
      ->getValue()['argument'];
    $title = $item
      ->getValue()['title'];
    $view = Views::getView($view_name);

    // Someone may have deleted the View.
    if (!is_object($view)) {
      continue;
    }

    // No access.
    if (!$view
      ->access($display_id)) {
      continue;
    }
    $view
      ->setDisplay($display_id);
    if ($argument) {
      $view->element['#cache']['keys'][] = $argument;
      $arguments = [
        $argument,
      ];
      if (preg_match('/\\//', $argument)) {
        $arguments = explode('/', $argument);
      }
      $node = \Drupal::routeMatch()
        ->getParameter('node');
      $token_service = \Drupal::token();
      if (is_array($arguments)) {
        foreach ($arguments as $index => $argument) {
          if (!empty($token_service
            ->scan($argument))) {
            $arguments[$index] = $token_service
              ->replace($argument, [
              'node' => $node,
            ]);
          }
        }
      }
      $view
        ->setArguments($arguments);
    }
    $view
      ->preExecute();
    $view
      ->execute($display_id);
    if ($title) {
      $title = $view
        ->getTitle();
      $title_render_array = [
        '#theme' => $view
          ->buildThemeFunctions('viewsreference__view_title'),
        '#title' => $title,
        '#view' => $view,
      ];
    }
    if ($this
      ->getSetting('plugin_types')) {
      if ($title) {
        $elements[$delta]['title'] = $title_render_array;
      }
    }
    $elements[$delta]['contents'] = $view
      ->buildRenderable($display_id);
  }
  return $elements;
}