public function MenuTreeFormatter::viewElements in Field Menu 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 FormatterInterface::viewElements
File
- src/
Plugin/ Field/ FieldFormatter/ MenuTreeFormatter.php, line 79
Class
- MenuTreeFormatter
- Plugin implementation of the 'field_menu_tree_formatter' formatter.
Namespace
Drupal\field_menu\Plugin\Field\FieldFormatterCode
public function viewElements(FieldItemListInterface $items, $langcode) {
$elements = [];
foreach ($items as $delta => $item) {
$menu_key_value_arr = explode(':', $item->menu_item_key);
$menu_name = isset($menu_key_value_arr[0]) && $menu_key_value_arr[0] ? $menu_key_value_arr[0] : NULL;
$parent = isset($menu_key_value_arr[1]) && $menu_key_value_arr[1] ? $menu_key_value_arr[1] : NULL;
$menu_link = isset($menu_key_value_arr[2]) && $menu_key_value_arr[2] ? $menu_key_value_arr[2] : NULL;
$menu_route = $parent == 'menu_link_content' ? $parent . ':' . $menu_link : $parent;
$menu_parameters = new MenuTreeParameters();
$menu_parameters
->setRoot($menu_route);
$menu_parameters
->onlyEnabledLinks();
if ($item->max_depth > 0) {
$menu_parameters
->setMaxDepth($item->max_depth);
}
if (!$item->include_root) {
$menu_parameters
->excludeRoot();
}
$tree = $this->menuLinkTree
->load($menu_name, $menu_parameters);
$manipulators = [
[
'callable' => 'menu.default_tree_manipulators:checkNodeAccess',
],
[
'callable' => 'menu.default_tree_manipulators:checkAccess',
],
[
'callable' => 'menu.default_tree_manipulators:generateIndexAndSort',
],
];
$tree = $this->menuLinkTree
->transform($tree, $manipulators);
$tree_render_array = $this->menuLinkTree
->build($tree);
$menu_title = trim($item->menu_title);
$elements[$delta] = [
'#theme' => 'field_menu_item',
'#title' => $menu_title,
'#tree' => $tree_render_array,
'#cache' => [
'contexts' => [
'languages:' . LanguageInterface::TYPE_INTERFACE,
],
],
];
}
return $elements;
}