Add info to a menu link

Public

Introduction

</> CopyGet raw version
text
  1. The menu_links table contains an 'options' column that basically can contains anything, provided you do not need to query on it (as it is a BLOB).
  2.  
  3. So you can store for example classes, attributes, icons, anything related to the menu link. The modules menu_attributes , menu_icons harness this functionality, but if you do not need every feature they provide, here's a little snippet that might help you.
  4.  
  5. Provided example: adding a target _blank attribute
</> CopyGet raw version
php
  1. /**
  2.  * Implements hook_form_FORM_ID_alter().
  3.  *
  4.  * @see mymodule_menu_link_alter().
  5.  */
  6. function mymodule_form_menu_edit_item_alter(&$form) {
  7. $item = $form['original_item']['#value'];
  8.  
  9. // Unset the previous value so that the new values get saved.
  10. if ($form['options']['#type'] == 'value') {
  11. unset($form['options']['#type']);
  12. unset($form['options']['#value']);
  13. $form['options']['#tree'] = TRUE;
  14. }
  15.  
  16. // Add a checkbox to open in a new window
  17. $form['options']['attributes']['target'] = array(
  18. '#type' => 'checkbox',
  19. '#title' => t('Open in a new window'),
  20. '#default_value' => !empty($item['options']['attributes']['target']),
  21. '#return_value' => '_blank',
  22. );
  23. }
  24.  
  25. /**
  26.  * Implements hook_menu_link_alter().
  27.  */
  28. function mymodule_menu_link_alter(&$item) {
  29. if (isset($item['options']['attributes']) && is_array($item['options']['attributes'])) {
  30. // Filter out blank attributes, so that the difference is visible in menu_link_save().
  31. foreach ($item['options']['attributes'] as $key => $value) {
  32. if ((is_array($value) && empty($value)) || is_string($value) && !drupal_strlen($value) || $value === 0) {
  33. unset($item['options']['attributes'][$key]);
  34. }
  35. }
  36. }
  37. }