Quantcast
Channel: Suburban Glory
Viewing all articles
Browse latest Browse all 101

Creating a pull down (nested) menu in Drupal 7

$
0
0

Special note: Don't follow this tutorial just download and use the Menu Block module instead.

Drupal was originally a developers toy but over the last few years the thrust of the CMS has been to try lower the entry point for non-technical users.

The administration section in version 7 is now far, far more user friendly to lay people and is closer to Wordpress in its logical layout and smooth navigation.

However, creating themes can still be a taxing process.

Out of the box, primary and secondary menus do not allow nested structures (unless you use them in the blocks). This isn't a CSS issue – it simple won't publish the necessary HTML despite being allowed to create a nested menu in the admin section.

Secondary and primary are placed into the theme by using the theme() function which creates a nested array like so:


        <?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'main-menu', 'class' => array('links', 'inline', 'clearfix')), 'heading' => t('Main menu'))); ?>

The above sets the id, classes and a header title and associates this with the menu in the database.

In order to allow nested menus it is necessary to replace the above code with this:


	<?php
$pid = variable_get('menu_main_links_source', 'main-menu');
$tree = menu_tree($pid);
$tree = str_replace(' class="menu"', '', $tree);
$main_menu = drupal_render($tree);
print $main_menu; 
?>

This uses three different inbuilt Drupal functions: variable_get(), menu_tree() and drupal_render().

To explain, persistent variables are created with the variable_set() function and are kept cached in the database to prevent easy retrieval with variable_get().

The id of the main menu – called 'main-menu' – is then used as a parameter in the menu_tree() function. This calls the nested array for the main menu.

The magic comes with the simple PHP str_replace() function. You are looking for the needle menu class in the menu nested array haystack and removing it.

Then it is stuck back together again using the drupal_render() function.

Isn't there a way of doing this with just the theme() function? Those nested arrays make my head spin. Perhaps a more experienced Drupalista can comment.


Viewing all articles
Browse latest Browse all 101

Trending Articles