The Web Developer's Blog has been discontinued. I am now maintaining a new blog that is related to my company, Blue Piccadilly. The most popular articles from this blog (by monthly page views) have already been republished on the new blog, and indeed those original pages on this blog are being redirected to their new location. I'll probably keep these pages up here for a while. At least until the domain expires.

Force a menu item to be active

05-Oct-2007
Filed under: Drupal, Drupal 5.x

Update: For Drupal 6.x, use the excellent Menu Trails module.

I run into this issue every time I build a new site in Drupal. I typically use the Views module to create a list of nodes. A possible use of this is a list of news items on a news page.

The URL of the view goes into my drupal menu. Click on the view and Drupal correctly highlights this as the active page. However, click on one of the nodes in the view and you lose your position in the menu. This is by design. Drupal has no way of knowing the relationship between your view and node you're currently viewing. It's open for debate whether this is functionality that could be added by the Views module, but that's a story for another day.

Here's a little bit of code I use to instruct Drupal as to which should be highlighted as the active menu position. The code snippet can be inserted in various places, but it's probably easiest to put it in your page.tpl.php or node.tpl.php files:

<?php
if ($node->type == 'news') {
 
$items[] = array(
   
'path' => '<front>',
  );
 
$items[] = array(
   
'path' => 'news',
  );
 
$items[] = array(
   
'path' => drupal_get_normal_path($path),
  );
 
menu_set_location($items);
}
?>

This passes an array of pages (basically the breadcrumb trail to the current page) to the drupal function 'menu_set_location'. Modify the node type in the if statement, as well as the array declaration to match your needs and you should be back in business.

Comments

So Rob,

Chocolate Fudge Brownies ... the solution to gain world peace or the cause of Western obesity?

It's a tricky one.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <i> <b> <cite> <code> <a>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.