Render a menu in a form

Components

Rendering a menu in a form requires a little bit more lines of code than rendering a View, but it is also very easy thanks to the menu.link_tree service. In the following example, we are rendering the main menu.

use Drupal\Core\Menu\MenuTreeParameters;

$menu_parameters = new MenuTreeParameters();
$manipulators = [
  ['callable' => 'menu.default_tree_manipulators:checkNodeAccess'],
  ['callable' => 'menu.default_tree_manipulators:checkAccess'],
  ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
];
$tree = \Drupal::menuTree()->load('main', $menu_parameters);
$tree = \Drupal::menuTree()->transform($tree, $manipulators);

$form['content'] = \Drupal::menuTree()->build($tree);

About the Author

Goran Nikolovski is a senior developer with over 10 years of experience turning ideas into scalable digital products—from web platforms and mobile apps to AI-powered tools. He is passionate about clean code, creative problem-solving, and shaping the future of digital development.

AI Assistant