menu_ui.module 19.9 KB
Newer Older
1 2
<?php

3 4
/**
 * @file
5 6 7
 * Allows administrators to customize the site's navigation menus.
 *
 * A menu (in this context) is a hierarchical collection of links, generally
8
 * used for navigation.
9 10
 */

11
use Drupal\Core\Breadcrumb\Breadcrumb;
12
use Drupal\Core\Cache\CacheableMetadata;
13
use Drupal\Core\Entity\EntityInterface;
14
use Drupal\Core\Block\BlockPluginInterface;
15
use Drupal\Core\Link;
16
use Drupal\Core\Menu\MenuLinkInterface;
17
use Drupal\Core\Form\FormStateInterface;
18
use Drupal\Core\Render\Element;
19
use Drupal\Core\Routing\RouteMatchInterface;
20
use Drupal\menu_link_content\Entity\MenuLinkContent;
21
use Drupal\node\NodeTypeInterface;
22
use Drupal\system\Entity\Menu;
23
use Drupal\node\NodeInterface;
24

25 26 27 28
/**
 * Maximum length of menu name as entered by the user. Database length is 32
 * and we add a menu- prefix.
 */
29
const MENU_MAX_MENU_NAME_LENGTH_UI = 27;
30

31
/**
32
 * Implements hook_help().
33
 */
34
function menu_ui_help($route_name, RouteMatchInterface $route_match) {
35 36
  switch ($route_name) {
    case 'help.page.menu_ui':
37 38
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
39
      $output .= '<p>' . t('The Menu UI module provides an interface for managing menus. A menu is a hierarchical collection of links, which can be within or external to the site, generally used for navigation. For more information, see the <a href=":menu">online documentation for the Menu UI module</a>.', array(':menu' => 'https://www.drupal.org/documentation/modules/menu/')) . '</p>';
40 41 42
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Managing menus') . '</dt>';
43
      $output .= '<dd>' . t('Users with the <em>Administer menus and menu items</em> permission can add, edit, and delete custom menus on the <a href=":menu">Menus page</a>. Custom menus can be special site menus, menus of external links, or any combination of internal and external links. You may create an unlimited number of additional menus, each of which will automatically have an associated block (if you have the <a href=":block_help">Block module</a> installed). By selecting <em>Edit menu</em>, you can add, edit, or delete links for a given menu. The links listing page provides a drag-and-drop interface for controlling the order of links, and creating a hierarchy within the menu.', array(':block_help' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('help.page', array('name' => 'block')) : '#', ':menu' => \Drupal::url('entity.menu.collection'))) . '</dd>';
44
      $output .= '<dt>' . t('Displaying menus') . '</dt>';
45
      $output .= '<dd>' . t('If you have the Block module enabled, then each menu that you create is rendered in a block that you enable and position on the <a href=":blocks">Block layout page</a>. In some <a href=":themes">themes</a>, the main menu and possibly the secondary menu will be output automatically; you may be able to disable this behavior on the <a href=":themes">theme\'s settings page</a>.', array(':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#', ':themes' => \Drupal::url('system.themes_page'), ':theme_settings' => \Drupal::url('system.theme_settings'))) . '</dd>';
46
      $output .= '</dl>';
47
      return $output;
48
  }
49
  if ($route_name == 'entity.menu.add_form' && \Drupal::moduleHandler()->moduleExists('block') && \Drupal::currentUser()->hasPermission('administer blocks')) {
50
    return '<p>' . t('You can enable the newly-created block for this menu on the <a href=":blocks">Block layout page</a>.', array(':blocks' => \Drupal::url('block.admin_display'))) . '</p>';
51
  }
52
  elseif ($route_name == 'entity.menu.collection' && \Drupal::moduleHandler()->moduleExists('block') && \Drupal::currentUser()->hasPermission('administer blocks')) {
53
    return '<p>' . t('Each menu has a corresponding block that is managed on the <a href=":blocks">Block layout page</a>.', array(':blocks' => \Drupal::url('block.admin_display'))) . '</p>';
54
  }
55 56
}

57
/**
58
 * Implements hook_entity_type_build().
59
 */
60
function menu_ui_entity_type_build(array &$entity_types) {
61 62
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  $entity_types['menu']
63 64
    ->setFormClass('add', 'Drupal\menu_ui\MenuForm')
    ->setFormClass('edit', 'Drupal\menu_ui\MenuForm')
65 66
    ->setFormClass('delete', 'Drupal\menu_ui\Form\MenuDeleteForm')
    ->setListBuilderClass('Drupal\menu_ui\MenuListBuilder')
67 68 69
    ->setLinkTemplate('add-form', '/admin/structure/menu/add')
    ->setLinkTemplate('delete-form', '/admin/structure/menu/manage/{menu}/delete')
    ->setLinkTemplate('edit-form', '/admin/structure/menu/manage/{menu}')
70 71
    ->setLinkTemplate('add-link-form', '/admin/structure/menu/manage/{menu}/add')
    ->setLinkTemplate('collection', '/admin/structure/menu');
72 73
}

74
/**
75
 * Implements hook_ENTITY_TYPE_insert( for menu entities.
76
 */
77
function menu_ui_menu_insert(Menu $menu) {
78 79
  menu_cache_clear_all();
  // Invalidate the block cache to update menu-based derivatives.
80
  if (\Drupal::moduleHandler()->moduleExists('block')) {
81
    \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
82
  }
83 84
}

85
/**
86
 * Implements hook_ENTITY_TYPE_update() for menu entities.
87
 */
88
function menu_ui_menu_update(Menu $menu) {
89
  menu_cache_clear_all();
90
  // Invalidate the block cache to update menu-based derivatives.
91
  if (\Drupal::moduleHandler()->moduleExists('block')) {
92
    \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
93
  }
94 95 96
}

/**
97
 * Implements hook_ENTITY_TYPE_predelete() for menu entities.
98
 */
99
function menu_ui_menu_predelete(Menu $menu) {
100
  // Delete all links from the menu.
101 102 103
  /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
  $menu_link_manager->deleteLinksInMenu($menu->id());
104
}
105

106
/**
107
 * Implements hook_ENTITY_TYPE_delete() for menu entities.
108
 */
109
function menu_ui_menu_delete(Menu $menu) {
110
  menu_cache_clear_all();
111

112
  // Invalidate the block cache to update menu-based derivatives.
113
  if (\Drupal::moduleHandler()->moduleExists('block')) {
114
    \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
115
  }
116 117
}

118
/**
119
 * Implements hook_block_view_BASE_BLOCK_ID_alter() for 'system_menu_block'.
120
 */
121
function menu_ui_block_view_system_menu_block_alter(array &$build, BlockPluginInterface $block) {
122 123
  if ($block->getBaseId() == 'system_menu_block') {
    $menu_name = $block->getDerivativeId();
124 125 126
    $build['#contextual_links']['menu'] = array(
      'route_parameters' => array('menu' => $menu_name),
    );
127 128 129
  }
}

130
/**
131 132 133 134 135 136
 * Helper function to create or update a menu link for a node.
 *
 * @param \Drupal\node\NodeInterface $node
 *   Node entity.
 * @param array $values
 *   Values for the menu link.
137
 */
138 139 140 141 142 143 144
function _menu_ui_node_save(NodeInterface $node, array $values) {
  /** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */
  if (!empty($values['entity_id'])) {
    $entity = MenuLinkContent::load($values['entity_id']);
  }
  else {
    // Create a new menu_link_content entity.
145
    $entity = MenuLinkContent::create(array(
146 147 148
      'link' => ['uri' => 'entity:node/' . $node->id()],
      'langcode' => $node->getUntranslated()->language()->getId(),
    ));
149
    $entity->enabled->value = 1;
150
  }
151 152 153 154 155 156
  $entity->title->value = trim($values['title']);
  $entity->description->value = trim($values['description']);
  $entity->menu_name->value = $values['menu_name'];
  $entity->parent->value = $values['parent'];
  $entity->weight->value = isset($values['weight']) ? $values['weight'] : 0;
  $entity->save();
157 158 159
}

/**
160
 * Implements hook_ENTITY_TYPE_predelete() for node entities.
161
 */
162
function menu_ui_node_predelete(EntityInterface $node) {
163 164 165
  // Delete all MenuLinkContent links that point to this node.
  /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
166
  $result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node->id()));
167 168

  if (!empty($result)) {
169 170 171 172 173
    foreach ($result as $id => $instance) {
      if ($instance->isDeletable() && strpos($id, 'menu_link_content:') === 0) {
        $instance->deleteLink();
      }
    }
174 175 176 177
  }
}

/**
178 179 180 181 182 183 184
 * Returns the definition for a menu link for the given node.
 *
 * @param \Drupal\node\NodeInterface $node
 *   The node entity.
 *
 * @return array
 *   An array that contains default values for the menu link form.
185
 */
186 187 188 189 190 191 192 193 194 195 196 197
function menu_ui_get_menu_link_defaults(NodeInterface $node) {
  // Prepare the definition for the edit form.
  /** @var \Drupal\node\NodeTypeInterface $node_type */
  $node_type = $node->type->entity;
  $menu_name = strtok($node_type->getThirdPartySetting('menu_ui', 'parent', 'main:'), ':');
  $defaults = FALSE;
  if ($node->id()) {
    $id = FALSE;
    // Give priority to the default menu
    $type_menus = $node_type->getThirdPartySetting('menu_ui', 'available_menus', array('main'));
    if (in_array($menu_name, $type_menus)) {
      $query = \Drupal::entityQuery('menu_link_content')
198
        ->condition('link.uri', 'node/' . $node->id())
199 200 201 202
        ->condition('menu_name', $menu_name)
        ->sort('id', 'ASC')
        ->range(0, 1);
      $result = $query->execute();
203

204
      $id = (!empty($result)) ? reset($result) : FALSE;
205
    }
206 207 208
    // Check all allowed menus if a link does not exist in the default menu.
    if (!$id && !empty($type_menus)) {
      $query = \Drupal::entityQuery('menu_link_content')
209
        ->condition('link.uri', 'entity:node/' . $node->id())
210 211 212 213
        ->condition('menu_name', array_values($type_menus), 'IN')
        ->sort('id', 'ASC')
        ->range(0, 1);
      $result = $query->execute();
214

215 216 217 218 219 220 221 222
      $id = (!empty($result)) ? reset($result) : FALSE;
    }
    if ($id) {
      $menu_link = MenuLinkContent::load($id);
      $defaults = array(
        'entity_id' => $menu_link->id(),
        'id' => $menu_link->getPluginId(),
        'title' => $menu_link->getTitle(),
223
        'title_max_length' => $menu_link->getFieldDefinitions()['title']->getSetting('max_length'),
224 225 226 227
        'description' => $menu_link->getDescription(),
        'menu_name' => $menu_link->getMenuName(),
        'parent' => $menu_link->getParentId(),
        'weight' => $menu_link->getWeight(),
228
      );
229
    }
230
  }
231 232

  if (!$defaults) {
233 234 235 236
    // Get the default max_length of a menu link title from the base field
    // definition.
    $field_definitions = \Drupal::entityManager()->getBaseFieldDefinitions('menu_link_content');
    $max_length = $field_definitions['title']->getSetting('max_length');
237 238 239 240
    $defaults = array(
      'entity_id' => 0,
      'id' => '',
      'title' => '',
241
      'title_max_length' => $max_length,
242 243 244 245 246 247 248
      'description' => '',
      'menu_name' => $menu_name,
      'parent' => '',
      'weight' => 0,
    );
  }
  return $defaults;
249 250
}

251
/**
252
 * Implements hook_form_BASE_FORM_ID_alter() for node_form.
253 254 255
 *
 * Adds menu item fields to the node form.
 *
256
 * @see menu_ui_form_node_form_submit()
257
 */
258
function menu_ui_form_node_form_alter(&$form, FormStateInterface $form_state) {
259
  // Generate a list of possible parents (not including this link or descendants).
260
  // @todo This must be handled in a #process handler.
261
  $node = $form_state->getFormObject()->getEntity();
262
  $defaults = menu_ui_get_menu_link_defaults($node);
263 264
  /** @var \Drupal\node\NodeTypeInterface $node_type */
  $node_type = $node->type->entity;
265 266 267
  /** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */
  $menu_parent_selector = \Drupal::service('menu.parent_form_selector');
  $menu_names = menu_ui_get_menus();
268
  $type_menus = $node_type->getThirdPartySetting('menu_ui', 'available_menus', array('main'));
269 270 271 272
  $available_menus = array();
  foreach ($type_menus as $menu) {
    $available_menus[$menu] = $menu_names[$menu];
  }
273 274
  if ($defaults['id']) {
    $default = $defaults['menu_name'] . ':' . $defaults['parent'];
275 276
  }
  else {
277
    $default = $node_type->getThirdPartySetting('menu_ui', 'parent', 'main:');
278
  }
279
  $parent_element = $menu_parent_selector->parentSelectElement($default, $defaults['id'], $available_menus);
280
  // If no possible parent menu items were found, there is nothing to display.
281
  if (empty($parent_element)) {
282 283 284 285
    return;
  }

  $form['menu'] = array(
286
    '#type' => 'details',
287
    '#title' => t('Menu settings'),
288
    '#access' => \Drupal::currentUser()->hasPermission('administer menu'),
289
    '#open' => (bool) $defaults['id'],
290
    '#group' => 'advanced',
291
    '#attached' => array(
292
      'library' => array('menu_ui/drupal.menu_ui'),
293 294 295 296 297 298 299 300
    ),
    '#tree' => TRUE,
    '#weight' => -2,
    '#attributes' => array('class' => array('menu-link-form')),
  );
  $form['menu']['enabled'] = array(
    '#type' => 'checkbox',
    '#title' => t('Provide a menu link'),
301
    '#default_value' => (int) (bool) $defaults['id'],
302 303 304 305 306 307 308
  );
  $form['menu']['link'] = array(
    '#type' => 'container',
    '#parents' => array('menu'),
    '#states' => array(
      'invisible' => array(
        'input[name="menu[enabled]"]' => array('checked' => FALSE),
309
      ),
310 311
    ),
  );
312

313
  // Populate the element with the link data.
314
  foreach (array('id', 'entity_id') as $key) {
315
    $form['menu']['link'][$key] = array('#type' => 'value', '#value' => $defaults[$key]);
316
  }
317

318
  $form['menu']['link']['title'] = array(
319 320
    '#type' => 'textfield',
    '#title' => t('Menu link title'),
321
    '#default_value' => $defaults['title'],
322
    '#maxlength' => $defaults['title_max_length'],
323
  );
324

325 326 327
  $form['menu']['link']['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
328
    '#default_value' => $defaults['description'],
329 330 331
    '#rows' => 1,
    '#description' => t('Shown when hovering over the menu link.'),
  );
332

333 334 335
  $form['menu']['link']['menu_parent'] = $parent_element;
  $form['menu']['link']['menu_parent']['#title'] = t('Parent item');
  $form['menu']['link']['menu_parent']['#attributes']['class'][] = 'menu-parent-select';
336

337
  $form['menu']['link']['weight'] = array(
338
    '#type' => 'number',
339
    '#title' => t('Weight'),
340
    '#default_value' => $defaults['weight'],
341
    '#description' => t('Menu links with lower weights are displayed before links with higher weights.'),
342
  );
343 344

  foreach (array_keys($form['actions']) as $action) {
345
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
346 347 348
      $form['actions'][$action]['#submit'][] = 'menu_ui_form_node_form_submit';
    }
  }
349 350
}

351
/**
352
 * Form submission handler for menu item field on the node form.
353
 *
354
 * @see menu_ui_form_node_form_alter()
355
 */
356 357
function menu_ui_form_node_form_submit($form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();
358
  if (!$form_state->isValueEmpty('menu')) {
359 360 361 362
    $values = $form_state->getValue('menu');
    if (empty($values['enabled'])) {
      if ($values['entity_id']) {
        $entity = MenuLinkContent::load($values['entity_id']);
363 364
        $entity->delete();
      }
365
    }
366
    elseif (trim($values['title']))  {
367 368
      // Decompose the selected menu parent option into 'menu_name' and 'parent',
      // if the form used the default parent selection widget.
369 370 371 372
      if (!empty($values['menu_parent'])) {
        list($menu_name, $parent) = explode(':', $values['menu_parent'], 2);
        $values['menu_name'] = $menu_name;
        $values['parent'] = $parent;
373
      }
374
      _menu_ui_node_save($node, $values);
375
    }
376 377 378
  }
}

379
/**
380 381
 * Implements hook_form_FORM_ID_alter().
 *
382
 * Adds menu options to the node type form.
383
 *
384
 * @see NodeTypeForm::form().
385
 * @see menu_ui_form_node_type_form_submit().
386
 */
387
function menu_ui_form_node_type_form_alter(&$form, FormStateInterface $form_state) {
388 389
  /** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */
  $menu_parent_selector = \Drupal::service('menu.parent_form_selector');
390
  $menu_options = menu_ui_get_menus();
391
  /** @var \Drupal\node\NodeTypeInterface $type */
392
  $type = $form_state->getFormObject()->getEntity();
393
  $form['menu'] = array(
394
    '#type' => 'details',
395 396
    '#title' => t('Menu settings'),
    '#attached' => array(
397
      'library' => array('menu_ui/drupal.menu_ui.admin'),
398 399 400 401 402 403
    ),
    '#group' => 'additional_settings',
  );
  $form['menu']['menu_options'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Available menus'),
404
    '#default_value' => $type->getThirdPartySetting('menu_ui', 'available_menus', array('main')),
405 406 407
    '#options' => $menu_options,
    '#description' => t('The menus available to place links in for this content type.'),
  );
408 409 410 411 412
  // @todo See if we can avoid pre-loading all options by changing the form or
  //   using a #process callback. https://www.drupal.org/node/2310319
  //   To avoid an 'illegal option' error after saving the form we have to load
  //   all available menu parents. Otherwise, it is not possible to dynamically
  //   add options to the list using ajax.
413 414
  $options_cacheability = new CacheableMetadata();
  $options = $menu_parent_selector->getParentSelectOptions('', NULL, $options_cacheability);
415 416 417
  $form['menu']['menu_parent'] = array(
    '#type' => 'select',
    '#title' => t('Default parent item'),
418
    '#default_value' => $type->getThirdPartySetting('menu_ui', 'parent', 'main:'),
419 420 421 422
    '#options' => $options,
    '#description' => t('Choose the menu item to be the default parent for a new link in the content authoring form.'),
    '#attributes' => array('class' => array('menu-title-select')),
  );
423
  $options_cacheability->applyTo($form['menu']['menu_parent']);
424

425
  $form['#validate'][] = 'menu_ui_form_node_type_form_validate';
426
  $form['#entity_builders'][] = 'menu_ui_form_node_type_form_builder';
427 428
}

429 430 431 432 433 434
/**
 * Submit handler for forms with menu options.
 *
 * @see menu_ui_form_node_type_form_alter().
 */
function menu_ui_form_node_type_form_validate(&$form, FormStateInterface $form_state) {
435
  $available_menus = array_filter($form_state->getValue('menu_options'));
436 437 438
  // If there is at least one menu allowed, the selected item should be in
  // one of them.
  if (count($available_menus)) {
439
    $menu_item_id_parts = explode(':', $form_state->getValue('menu_parent'));
440
    if (!in_array($menu_item_id_parts[0], $available_menus)) {
441
      $form_state->setErrorByName('menu_parent', t('The selected menu item is not under one of the selected menus.'));
442 443 444
    }
  }
  else {
445
    $form_state->setValue('menu_parent', '');
446 447 448
  }
}

449
/**
450
 * Entity builder for the node type form with menu options.
451
 *
452
 * @see menu_ui_form_node_type_form_alter().
453
 */
454 455 456
function menu_ui_form_node_type_form_builder($entity_type, NodeTypeInterface $type, &$form, FormStateInterface $form_state) {
  $type->setThirdPartySetting('menu_ui', 'available_menus', array_values(array_filter($form_state->getValue('menu_options'))));
  $type->setThirdPartySetting('menu_ui', 'parent', $form_state->getValue('menu_parent'));
457 458
}

459 460 461
/**
 * Return an associative array of the custom menus names.
 *
462 463 464
 * @param bool $all
 *   (optional) If FALSE return only user-added menus, or if TRUE also include
 *   the menus defined by the system. Defaults to TRUE.
465 466
 *
 * @return array
467 468 469
 *   An array with the machine-readable names as the keys, and human-readable
 *   titles as the values.
 */
470
function menu_ui_get_menus($all = TRUE) {
471
  if ($custom_menus = Menu::loadMultiple()) {
472 473 474 475
    if (!$all) {
      $custom_menus = array_diff_key($custom_menus, menu_list_system_menus());
    }
    foreach ($custom_menus as $menu_name => $menu) {
476
      $custom_menus[$menu_name] = $menu->label();
477 478
    }
    asort($custom_menus);
479
  }
480
  return $custom_menus;
481
}
482 483

/**
484
 * Implements hook_preprocess_HOOK() for block templates.
485
 */
486 487
function menu_ui_preprocess_block(&$variables) {
  if ($variables['configuration']['provider'] == 'menu_ui') {
488
    $variables['attributes']['role'] = 'navigation';
489 490
  }
}
491 492 493 494 495


/**
 * Implements hook_system_breadcrumb_alter().
 */
496
function menu_ui_system_breadcrumb_alter(Breadcrumb &$breadcrumb, RouteMatchInterface $route_match, array $context) {
497 498 499 500 501
  // Custom breadcrumb behavior for editing menu links, we append a link to
  // the menu in which the link is found.
  if (($route_match->getRouteName() == 'menu_ui.link_edit') && $menu_link = $route_match->getParameter('menu_link_plugin')) {
    if (($menu_link instanceof MenuLinkInterface)) {
      // Add a link to the menu admin screen.
502
      $menu = Menu::load($menu_link->getMenuName());
503
      $breadcrumb->addLink(Link::createFromRoute($menu->label(), 'entity.menu.edit_form', ['menu' => $menu->id()]));
504 505 506
    }
  }
}