Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get all the menu items below a certain parent in drupal?

Tags:

menu

drupal

I really only need the mlid and title text for the first level below a certain menu item. Here's what I'm doing at the moment. (It works, but I suspect there may be a more drupal-y way.):

/**
 * Get all the children menu items below 'Style Guide' and put them in this format:
 * $menu_items[mlid] = 'menu-title'
 * @return array
 */
function mymod_get_menu_items() {
    $tree = menu_tree_all_data('primary-links');
    $branches = $tree['49952 Parent Item 579']['below']; // had to dig for that ugly key
    $menu_items = array();
    foreach ($branches as $menu_item) {
        $menu_items[$menu_item['link']['mlid']] = $menu_item['link']['title'];
    }
    return $menu_items;
}

Is there?

like image 405
sprugman Avatar asked Apr 26 '10 20:04

sprugman


2 Answers

Actually there is an easy way to get that information by using menu_build_tree():

// Set $path to the internal Drupal path of the parent or
// to NULL for the current path 
$path = 'node/123';
$parent = menu_link_get_preferred($path);
$parameters = array(
    'active_trail' => array($parent['plid']),
    'only_active_trail' => FALSE,
    'min_depth' => $parent['depth']+1,
    'max_depth' => $parent['depth']+1,
    'conditions' => array('plid' => $parent['mlid']),
  );

$children = menu_build_tree($parent['menu_name'], $parameters);

$children contains all information you need. menu_build_tree() checks access or translation related restrictions too so you only get what the user really should see.

like image 112
Bernhard Fürst Avatar answered Oct 19 '22 19:10

Bernhard Fürst


afaik, there isn't (i hope i am wrong). for the while, instead of digging for ugly keys, you can turn your function into a more abstract helper function by simply adding a foreach ($tree). then you can use your own logic to output what you want (mlid, in this case). here is my suggestion:


/**
 * Get the children of a menu item in a given menu.
 *
 * @param string $title
 *   The title of the parent menu item.
 * @param string $menu
 *   The internal menu name.
 * 
 * @return array
 *   The children of the given parent. 
 */
function MY_MODULE_submenu_tree_all_data($title, $menu = 'primary-links') {
  $tree = menu_tree_all_data($menu);
  foreach ($tree as $branch) {
    if ($branch['link']['title'] == $title) {
      return $branch['below'];
    }
  }
  return array();
}
like image 23
Capi Etheriel Avatar answered Oct 19 '22 21:10

Capi Etheriel