Drupal 6 – Pre-Popluate Menu Parents with jQuery

Here’s a fun one.
I wanted the menu parent to be pre-populated on node creation.

Use case:

  • When a content editor creates a new ‘Electronic Flyer’ it will be added to the per-determined menu: Primary Links >> Resources >> Electronic Flyers.

Here’s a screenshot demonstrating the pre-filled out menu parent:
image of the menu fieldset

I wanted to get this working in a hurry so I crafted the code and dropped it into a js_injector instance.
Here’s the essential js:

//populate menu parent
$('#edit-menu-parent').val('primary-links:3489');
if($('.menu-item-form').length > 0) {
  //open 'Menu settings' if closed:
  $('.menu-item-form.collapsed a').click();
}

In this scenario I only run the code on “node/add/electronic-flyers” and so I can get away with setting the menu parent with a fixed value: primary-links:3489. That’s the menu id for “Electronic Flyers” (Primary Links >> Resources >> Electronic Flyers).
That line is really the key:

$('#edit-menu-parent').val('primary-links:3489');

The next lines are for convenience.

if($('.menu-item-form').length > 0) {
  //open 'Menu settings' if closed:
  $('.menu-item-form.collapsed a').click();
}

That checks to see if the menu fieldset is loaded. If so, and it’s collapsed the script ‘clicks’ the handle to open the fieldset for the user.
The collapsed ‘Menu settings’ fieldset is easy to overlook, so opening it helps ensure that a menu item gets created.
After all, what’s the point of presetting the menu parent if the menu settings are hidden from view!

That code goes into a Drupal.behaviors wrapper and runs on page load.

Drupal.behaviors.pre_set_menu_item = function (context) {
  //run only if there is a context var
  if(typeof context !== 'undefined'){
    if(typeof context == 'object' && context.toString().indexOf('HTMLDocument')!=-1){ //page load
      /*
      Check the type of the context var and type. Process if context = [object HTMLDocument]
      Note: when context == [object HTMLDocument] then this is page load. You may want some script to run only on page load. Some not and some all the time.
      */

      //populate menu parent
      $('#edit-menu-parent').val('primary-links:3489');
      //open 'Menu settings' if closed:
      if($('.menu-item-form').length > 0) {
        $('.menu-item-form.collapsed a').click();
      }

    } //end if(typeof context == 'object' && context.toString().indexOf('HTMLDocument')!=-1) page load
  } //end if(typeof context !== 'undefined'){
} //end pre_set_menu_item

Bingo. Menus aren’t quite so cumbersome anymore.

Ultimately it would be cool to make this more flexible. I had another version in the works that looked for the ‘parent’ url var. For ex: /node/add/electronic-flyers?parent=3489
That takes a bit more code and so a custom module may be in order at some point.

Leave a Comment