Automatically Copying The Node Title To The Menu Title In Drupal 6

One new feature of Drupal 7 is that any title you give a node will be copied to the menu title field when you create a menu item. I wanted to replicate this functionality in Drupal 6 and so I created a function that did just that. I have used this function a few times in different projects so I'm posting it here.

This code uses the drupal_add_js() function to push a small amount of JavaScript code into the page when a node is added or edited. The hook hook_init() is used to add this content as it is run very early on in the Drupal boot cycle. I have tried putting this code into other hooks (like hook_preprocess_page()) but it isn't included, I would look into this further but this solution seems to work well.

The JavaScript added is a bit of jQuery code that looks at the title field of the node and will copy it to the menu title field if anything has been entered. It makes sure that nothing is already in the menu title field before doing the copying as it would otherwise overwrite any custom titles added. Not all nodes are menu items so the code is only run if the user clicks into the menu field, which replicates the Drupal 7 functionality.

/**
 * Implementation of HOOK_init(). Used to add javascript to the node add and edit pages that copies the node title to the menu title field.
 */
function mymodule_init() {
    if ((arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'edit') || (arg(0) == 'node' && arg(1) == 'add' && arg(2) != '')) {
	drupal_add_js("
    $(document).ready(function() {
        $('#edit-menu-link-title').focus(function() {
            if(this.value == '') {
                this.value = $('#edit-title').val();
            }
        });
        $('#edit-path').focus(function() {
            if(this.v == '') {
                this.value = $('#edit-title').val().toLowerCase().replace(' ', '_');
            }
        });
        $('#edit-menu-link-title').keydown(function(event) {
            if ($('#edit-menu-link-title').val().length < 80) {
                $('#edit-menu-link-title').removeClass('error');
            } else {
                $('#edit-menu-link-title').addClass('error');
            }
        });
    });
", 'inline');
    }
}

This code also does a small amount of validation to encourage users from adding massive menu titles by adding an "error" class to the field if they add a long title. This is currently set to 80 characters, which seems like a good limit.

To use this function just add it to one of your own custom modules or even create a module for it.

Comments

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
5 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.