Thursday 20 April 2017

Drupal 8 Get list of all menus

To get the list of all menus, Drupal 7 provides us a function "menu_get_menus()" which return a list of all menus with their machine name.
In D8 for some time this function will exist, but in future, this will be deprecated and in Drupal 9 this will be removed.
So if you are using this function then this will work but any update of Drupal 8 will deprecate this function.So to avoiding this problem use following code:

Just include this class
use Drupal\system\Entity\Menu;

then write this line, which returen an array of menu objects.
$menus = Menu::loadMultiple();

For only get list of menus, you can use this

    $menus = array();
    $menu_types = Menu::loadMultiple();

    if (!empty($menu_types)) {
      foreach ($menu_types as $menu_name => $menu) {
        $menus[$menu_name] = $menu->label();
      }
      asort($menus);
    }

No comments:

Post a Comment

Thanks!