menu_ui.module 19.4 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\Cache\CacheableMetadata;
12
use Drupal\Core\Entity\EntityInterface;
13
use Drupal\Core\Block\BlockPluginInterface;
14
use Drupal\Core\Link;
15
use Drupal\Core\Menu\MenuLinkInterface;
16
use Drupal\Core\Form\FormStateInterface;
17
use Drupal\Core\Render\Element;
18
use Drupal\Core\Routing\RouteMatchInterface;
19
use Drupal\menu_link_content\Entity\MenuLinkContent;
20
use Drupal\node\NodeTypeInterface;
21
use Drupal\system\Entity\Menu;
22
use Symfony\Component\HttpFoundation\JsonResponse;
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')) {
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')) {
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 145 146 147 148
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.
    $entity = entity_create('menu_link_content', array(
      '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 223 224 225 226
      $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(),
        'description' => $menu_link->getDescription(),
        'menu_name' => $menu_link->getMenuName(),
        'parent' => $menu_link->getParentId(),
        'weight' => $menu_link->getWeight(),
227
      );
228
    }
229
  }
230 231 232 233 234 235 236 237 238 239 240 241 242

  if (!$defaults) {
    $defaults = array(
      'entity_id' => 0,
      'id' => '',
      'title' => '',
      'description' => '',
      'menu_name' => $menu_name,
      'parent' => '',
      'weight' => 0,
    );
  }
  return $defaults;
243 244
}

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

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

307
  // Populate the element with the link data.
308
  foreach (array('id', 'entity_id') as $key) {
309
    $form['menu']['link'][$key] = array('#type' => 'value', '#value' => $defaults[$key]);
310
  }
311

312
  $form['menu']['link']['title'] = array(
313 314
    '#type' => 'textfield',
    '#title' => t('Menu link title'),
315
    '#default_value' => $defaults['title'],
316
  );
317

318 319 320
  $form['menu']['link']['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
321
    '#default_value' => $defaults['description'],
322 323 324
    '#rows' => 1,
    '#description' => t('Shown when hovering over the menu link.'),
  );
325

326 327 328
  $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';
329

330
  $form['menu']['link']['weight'] = array(
331
    '#type' => 'number',
332
    '#title' => t('Weight'),
333
    '#default_value' => $defaults['weight'],
334
    '#description' => t('Menu links with lower weights are displayed before links with higher weights.'),
335
  );
336 337

  foreach (array_keys($form['actions']) as $action) {
338
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
339 340 341
      $form['actions'][$action]['#submit'][] = 'menu_ui_form_node_form_submit';
    }
  }
342 343
}

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

372
/**
373 374
 * Implements hook_form_FORM_ID_alter().
 *
375
 * Adds menu options to the node type form.
376
 *
377
 * @see NodeTypeForm::form().
378
 * @see menu_ui_form_node_type_form_submit().
379
 */
380
function menu_ui_form_node_type_form_alter(&$form, FormStateInterface $form_state) {
381 382
  /** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */
  $menu_parent_selector = \Drupal::service('menu.parent_form_selector');
383
  $menu_options = menu_ui_get_menus();
384
  /** @var \Drupal\node\NodeTypeInterface $type */
385
  $type = $form_state->getFormObject()->getEntity();
386
  $form['menu'] = array(
387
    '#type' => 'details',
388 389
    '#title' => t('Menu settings'),
    '#attached' => array(
390
      'library' => array('menu_ui/drupal.menu_ui.admin'),
391 392 393 394 395 396
    ),
    '#group' => 'additional_settings',
  );
  $form['menu']['menu_options'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Available menus'),
397
    '#default_value' => $type->getThirdPartySetting('menu_ui', 'available_menus', array('main')),
398 399 400
    '#options' => $menu_options,
    '#description' => t('The menus available to place links in for this content type.'),
  );
401 402 403 404 405
  // @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.
406 407
  $options_cacheability = new CacheableMetadata();
  $options = $menu_parent_selector->getParentSelectOptions('', NULL, $options_cacheability);
408 409 410
  $form['menu']['menu_parent'] = array(
    '#type' => 'select',
    '#title' => t('Default parent item'),
411
    '#default_value' => $type->getThirdPartySetting('menu_ui', 'parent', 'main:'),
412 413 414 415
    '#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')),
  );
416
  $options_cacheability->applyTo($form['menu']['menu_parent']);
417

418
  $form['actions']['submit']['#validate'][] = 'menu_ui_form_node_type_form_validate';
419
  $form['#entity_builders'][] = 'menu_ui_form_node_type_form_builder';
420 421
}

422 423 424 425 426 427
/**
 * 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) {
428
  $available_menus = array_filter($form_state->getValue('menu_options'));
429 430 431
  // If there is at least one menu allowed, the selected item should be in
  // one of them.
  if (count($available_menus)) {
432
    $menu_item_id_parts = explode(':', $form_state->getValue('menu_parent'));
433
    if (!in_array($menu_item_id_parts[0], $available_menus)) {
434
      $form_state->setErrorByName('menu_parent', t('The selected menu item is not under one of the selected menus.'));
435 436 437
    }
  }
  else {
438
    $form_state->setValue('menu_parent', '');
439 440 441
  }
}

442
/**
443
 * Entity builder for the node type form with menu options.
444
 *
445
 * @see menu_ui_form_node_type_form_alter().
446
 */
447 448 449
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'));
450 451
}

452 453 454
/**
 * Return an associative array of the custom menus names.
 *
455 456 457
 * @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.
458 459
 *
 * @return array
460 461 462
 *   An array with the machine-readable names as the keys, and human-readable
 *   titles as the values.
 */
463
function menu_ui_get_menus($all = TRUE) {
464
  if ($custom_menus = Menu::loadMultiple()) {
465 466 467 468
    if (!$all) {
      $custom_menus = array_diff_key($custom_menus, menu_list_system_menus());
    }
    foreach ($custom_menus as $menu_name => $menu) {
469
      $custom_menus[$menu_name] = $menu->label();
470 471
    }
    asort($custom_menus);
472
  }
473
  return $custom_menus;
474
}
475 476

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


/**
 * Implements hook_system_breadcrumb_alter().
 */
function menu_ui_system_breadcrumb_alter(array &$breadcrumb, RouteMatchInterface $route_match, array $context) {
  // 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.
495
      $menu = Menu::load($menu_link->getMenuName());
496
      $breadcrumb[] = Link::createFromRoute($menu->label(), 'entity.menu.edit_form', array('menu' => $menu->id()));
497 498 499
    }
  }
}