You are here

public function MenuReferenceFormatter::viewElements in Menu Reference Render (Formatter) 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldFormatter/MenuReferenceFormatter.php \Drupal\menu_reference_render\Plugin\Field\FieldFormatter\MenuReferenceFormatter::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/MenuReferenceFormatter.php, line 25

Class

MenuReferenceFormatter
Plugin implementation of the 'menu_reference_render' formatter.

Namespace

Drupal\menu_reference_render\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  $elements = [];
  foreach ($this
    ->getEntitiesToView($items, $langcode) as $entity) {
    $menu_name = $entity
      ->get('id');
    $menu_tree = \Drupal::menuTree();

    // Build the typical default set of menu tree parameters.
    $parameters = $menu_tree
      ->getCurrentRouteMenuTreeParameters($menu_name);

    // Load the tree based on this set of parameters.
    $tree = $menu_tree
      ->load($menu_name, $parameters);
    $manipulators = [
      [
        'callable' => 'menu.default_tree_manipulators:checkNodeAccess',
      ],
      [
        'callable' => 'menu.default_tree_manipulators:checkAccess',
      ],
      [
        'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
      ],
    ];
    $tree = $menu_tree
      ->transform($tree, $manipulators);
    $elements[] = $menu_tree
      ->build($tree);
  }
  return $elements;
}