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

13th April 2011

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.

  1. /**
  2.  * 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.
  3.  */
  4. function mymodule_init() {
  5. if ((arg(0) == 'node' && is_numeric(arg(1)) && arg(2) == 'edit') || (arg(0) == 'node' && arg(1) == 'add' && arg(2) != '')) {
  6. drupal_add_js("
  7. $(document).ready(function() {
  8. $('#edit-menu-link-title').focus(function() {
  9. if(this.value == '') {
  10. this.value = $('#edit-title').val();
  11. }
  12. });
  13. $('#edit-path').focus(function() {
  14. if(this.v == '') {
  15. this.value = $('#edit-title').val().toLowerCase().replace(' ', '_');
  16. }
  17. });
  18. $('#edit-menu-link-title').keydown(function(event) {
  19. if ($('#edit-menu-link-title').val().length < 80) {
  20. $('#edit-menu-link-title').removeClass('error');
  21. } else {
  22. $('#edit-menu-link-title').addClass('error');
  23. }
  24. });
  25. });
  26. ", 'inline');
  27. }
  28. }

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.