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

Dries's avatar
 
Dries committed
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.
Dries's avatar
 
Dries committed
9 10
 */

11
use Drupal\Core\Entity\EntityInterface;
12
use Drupal\block\BlockPluginInterface;
13
use Drupal\Core\Menu\MenuLinkInterface;
14
use Drupal\Core\Form\FormStateInterface;
15
use Drupal\Core\Render\Element;
16
use Drupal\Core\Routing\RouteMatchInterface;
17
use Drupal\menu_link_content\Entity\MenuLinkContent;
18
use Drupal\node\NodeTypeInterface;
19
use Drupal\system\Entity\Menu;
20
use Symfony\Component\HttpFoundation\JsonResponse;
21
use Drupal\node\NodeInterface;
22

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

29
/**
30
 * Implements hook_help().
31
 */
32
function menu_ui_help($route_name, RouteMatchInterface $route_match) {
33 34
  switch ($route_name) {
    case 'help.page.menu_ui':
35 36
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
37
      $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://drupal.org/documentation/modules/menu/')) . '</p>';
38 39 40
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Managing menus') . '</dt>';
41
      $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::url('help.page', array('name' => 'block')), '!menu' => \Drupal::url('menu_ui.overview_page'))) . '</dd>';
42
      $output .= '<dt>' . t('Displaying menus') . '</dt>';
43
      $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>';
44
      $output .= '</dl>';
45
      return $output;
46
  }
47 48
  if ($route_name == 'menu_ui.menu_add' && \Drupal::moduleHandler()->moduleExists('block')) {
    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>';
49
  }
50
  elseif ($route_name == 'menu_ui.overview_page' && \Drupal::moduleHandler()->moduleExists('block')) {
51
    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>';
52
  }
53 54
}

55
/**
56
 * Implements hook_permission().
57
 */
58
function menu_ui_permission() {
59
  return array(
60
    'administer menu' => array(
61
      'title' => t('Administer menus and menu items'),
62
    ),
63
  );
64 65
}

66
/**
67
 * Implements hook_entity_type_build().
68
 */
69
function menu_ui_entity_type_build(array &$entity_types) {
70 71
  /** @var $entity_types \Drupal\Core\Entity\EntityTypeInterface[] */
  $entity_types['menu']
72 73
    ->setFormClass('add', 'Drupal\menu_ui\MenuForm')
    ->setFormClass('edit', 'Drupal\menu_ui\MenuForm')
74 75
    ->setFormClass('delete', 'Drupal\menu_ui\Form\MenuDeleteForm')
    ->setListBuilderClass('Drupal\menu_ui\MenuListBuilder')
76
    ->setLinkTemplate('add-form', 'menu_ui.menu_add')
77
    ->setLinkTemplate('delete-form', 'menu_ui.delete_menu')
78 79
    ->setLinkTemplate('edit-form', 'menu_ui.menu_edit')
    ->setLinkTemplate('add-link-form', 'menu_link_content.link_add');
80 81
}

82

83
/**
84
 * Implements hook_theme().
85
 */
86
function menu_ui_theme() {
87 88
  return array(
    'menu_overview_form' => array(
89
      'file' => 'menu_ui.admin.inc',
90
      'render element' => 'form',
91 92 93 94
    ),
  );
}

95
/**
96
 * Implements hook_ENTITY_TYPE_insert( for menu entities.
97
 */
98
function menu_ui_menu_insert(Menu $menu) {
99 100
  menu_cache_clear_all();
  // Invalidate the block cache to update menu-based derivatives.
101
  if (\Drupal::moduleHandler()->moduleExists('block')) {
102
    \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
103
  }
104 105
}

106
/**
107
 * Implements hook_ENTITY_TYPE_update() for menu entities.
108
 */
109
function menu_ui_menu_update(Menu $menu) {
110
  menu_cache_clear_all();
111
  // Invalidate the block cache to update menu-based derivatives.
112
  if (\Drupal::moduleHandler()->moduleExists('block')) {
113
    \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
114
  }
115 116 117
}

/**
118
 * Implements hook_ENTITY_TYPE_predelete() for menu entities.
119
 */
120
function menu_ui_menu_predelete(Menu $menu) {
121
  // Delete all links from the menu.
122 123 124
  /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
  $menu_link_manager->deleteLinksInMenu($menu->id());
125
}
126

127
/**
128
 * Implements hook_ENTITY_TYPE_delete() for menu entities.
129
 */
130
function menu_ui_menu_delete(Menu $menu) {
131
  menu_cache_clear_all();
132

133
  // Invalidate the block cache to update menu-based derivatives.
134
  if (\Drupal::moduleHandler()->moduleExists('block')) {
135
    \Drupal::service('plugin.manager.block')->clearCachedDefinitions();
136
  }
137 138
}

139
/**
140
 * Implements hook_block_view_BASE_BLOCK_ID_alter() for 'system_menu_block'.
141
 */
142
function menu_ui_block_view_system_menu_block_alter(array &$build, BlockPluginInterface $block) {
143
  // Add contextual links for system menu blocks.
144
  $menus = menu_list_system_menus();
145
  $menu_name = $block->getDerivativeId();
146
  if (isset($menus[$menu_name]) && isset($build['content'])) {
147 148 149
    $build['#contextual_links']['menu'] = array(
      'route_parameters' => array('menu' => $menu_name),
    );
150 151 152
  }
}

153
/**
154
 * Implements hook_ENTITY_TYPE_insert() for node entities.
155
 */
156 157
function menu_ui_node_insert(EntityInterface $node) {
  menu_ui_node_save($node);
158 159 160
}

/**
161
 * Implements hook_ENTITY_TYPE_update() for node entities.
162
 */
163 164
function menu_ui_node_update(EntityInterface $node) {
  menu_ui_node_save($node);
165 166
}

167
/**
168
 * Implements hook_ENTITY_TYPE_insert() for node_type entities.
169
 */
170
function menu_ui_node_type_insert(NodeTypeInterface $type) {
171 172 173
  if ($type->isSyncing()) {
    return;
  }
174 175
  \Drupal::config('menu.entity.node.' . $type->id())
    ->set('available_menus', array('main'))
176
    ->set('parent', 'main:')
177 178 179 180
    ->save();
}

/**
181
 * Implements hook_ENTITY_TYPE_delete() for node_type entities.
182
 */
183
function menu_ui_node_type_delete(NodeTypeInterface $type) {
184 185 186
  if ($type->isSyncing()) {
    return;
  }
187 188 189
  \Drupal::config('menu.entity.node.' . $type->id())->delete();
}

190
/**
191
 * Helper for hook_ENTITY_TYPE_insert() and hook_ENTITY_TYPE_update() for nodes.
192
 */
193
function menu_ui_node_save(EntityInterface $node) {
194
  if (!empty($node->menu)) {
195
    /** @var \Drupal\menu_link_content\MenuLinkContentInterface $entity */
196 197 198 199 200 201 202 203 204 205
    $definition = $node->menu;
    if (trim($definition['title'])) {
      if (!empty($definition['entity_id'])) {
        $entity = entity_load('menu_link_content', $definition['entity_id']);
        $entity->hidden->value = 0;
        $entity->title->value = trim($definition['title']);
        $entity->description->value = trim($definition['description']);
        $entity->menu_name->value = $definition['menu_name'];
        $entity->parent->value = $definition['parent'];
        $entity->weight->value = isset($definition['weight']) ? $definition['weight'] : 0;
206 207
      }
      else {
208 209 210 211
        // Create a new menu_link_content entity.
        $entity = entity_create('menu_link_content', array(
          'title' => trim($definition['title']),
          'description' => trim($definition['description']),
212
          'route_name' => 'entity.node.canonical',
213 214 215 216 217 218 219 220
          'route_parameters' => array('node' => $node->id()),
          'menu_name' => $definition['menu_name'],
          'parent' => $definition['parent'],
          'weight' => isset($definition['weight']) ? $definition['weight'] : 0,
          'hidden' => 0,
          'bundle' => 'menu_link_content',
          'langcode' => $node->getUntranslated()->language()->id,
        ));
221
      }
222
      if (!$entity->save()) {
223
        drupal_set_message(t('There was an error saving the menu link.'), 'error');
224
      }
225 226 227 228 229
    }
  }
}

/**
230
 * Implements hook_ENTITY_TYPE_predelete() for node entities.
231
 */
232
function menu_ui_node_predelete(EntityInterface $node) {
233 234 235
  // 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');
236
  $result = $menu_link_manager->loadLinksByRoute('entity.node.canonical', array('node' => $node->id()));
237 238

  if (!empty($result)) {
239 240 241 242 243
    foreach ($result as $id => $instance) {
      if ($instance->isDeletable() && strpos($id, 'menu_link_content:') === 0) {
        $instance->deleteLink();
      }
    }
244 245 246 247
  }
}

/**
248
 * Implements hook_node_prepare_form().
249
 */
250
function menu_ui_node_prepare_form(NodeInterface $node, $operation, FormStateInterface $form_state) {
251
  if (empty($form_state['menu_link_definition'])) {
252
    // Prepare the node for the edit form so that $node->menu always exists.
253 254
    $node_type_config = \Drupal::config('menu.entity.node.' . $node->getType());
    $menu_name = strtok($node_type_config->get('parent'), ':');
255
    $definition = FALSE;
256
    if ($node->id()) {
257
      $id = FALSE;
258
      // Give priority to the default menu
259
      $type_menus = $node_type_config->get('available_menus');
260
      if (in_array($menu_name, $type_menus)) {
261
        $query = \Drupal::entityQuery('menu_link_content')
262
          ->condition('route_name', 'entity.node.canonical')
263
          ->condition('route_parameters', serialize(array('node' => $node->id())))
264
          ->condition('menu_name', $menu_name)
265
          ->sort('id', 'ASC')
266 267 268
          ->range(0, 1);
        $result = $query->execute();

269
        $id = (!empty($result)) ? reset($result) : FALSE;
270 271
      }
      // Check all allowed menus if a link does not exist in the default menu.
272 273
      if (!$id && !empty($type_menus)) {
        $query = \Drupal::entityQuery('menu_link_content')
274
          ->condition('route_name', 'entity.node.canonical')
275
          ->condition('route_parameters', serialize(array('node' => $node->id())))
276
          ->condition('menu_name', array_values($type_menus), 'IN')
277
          ->sort('id', 'ASC')
278 279 280
          ->range(0, 1);
        $result = $query->execute();

281
        $id = (!empty($result)) ? reset($result) : FALSE;
282
      }
283 284 285 286 287 288 289 290 291 292 293
      if ($id) {
        $menu_link = MenuLinkContent::load($id);
        $definition = 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(),
        );
294 295
      }
    }
296

297 298 299 300 301 302
    if (!$definition) {
      $definition = array(
        'entity_id' => 0,
        'id' => '',
        'title' => '',
        'description' => '',
303
        'menu_name' => $menu_name,
304 305 306
        'parent' => '',
        'weight' => 0,
      );
307
    }
308
    // Set default values.
309
    $form_state['menu_link_definition'] = $definition;
310 311 312
  }
}

313
/**
314
 * Implements hook_form_BASE_FORM_ID_alter() for node_form.
315 316 317
 *
 * Adds menu item fields to the node form.
 *
318
 * @see menu_ui_node_submit()
319
 */
320
function menu_ui_form_node_form_alter(&$form, FormStateInterface $form_state) {
321
  // Generate a list of possible parents (not including this link or descendants).
322
  // @todo This must be handled in a #process handler.
323
  $node = $form_state['controller']->getEntity();
324
  $definition = $form_state['menu_link_definition'];
325
  $type = $node->getType();
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
  /** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */
  $menu_parent_selector = \Drupal::service('menu.parent_form_selector');
  $menu_names = menu_ui_get_menus();
  $type_menus = \Drupal::config("menu.entity.node.$type")->get('available_menus');
  $available_menus = array();
  foreach ($type_menus as $menu) {
    $available_menus[$menu] = $menu_names[$menu];
  }
  if ($definition['id']) {
    $default = $definition['menu_name'] . ':' . $definition['parent'];
  }
  else {
    $default = \Drupal::config('menu.entity.node.'.$type)->get('parent');
  }
  $parent_element = $menu_parent_selector->parentSelectElement($default,  $definition['id'], $available_menus);
341
  // If no possible parent menu items were found, there is nothing to display.
342
  if (empty($parent_element)) {
343 344 345 346
    return;
  }

  $form['menu'] = array(
347
    '#type' => 'details',
348
    '#title' => t('Menu settings'),
349
    '#access' => \Drupal::currentUser()->hasPermission('administer menu'),
350
    '#open' => (bool) $definition['id'],
351
    '#group' => 'advanced',
352
    '#attached' => array(
353
      'library' => array('menu/drupal.menu'),
354 355 356 357 358 359 360 361
    ),
    '#tree' => TRUE,
    '#weight' => -2,
    '#attributes' => array('class' => array('menu-link-form')),
  );
  $form['menu']['enabled'] = array(
    '#type' => 'checkbox',
    '#title' => t('Provide a menu link'),
362
    '#default_value' => (int) (bool) $definition['id'],
363 364 365 366 367 368 369
  );
  $form['menu']['link'] = array(
    '#type' => 'container',
    '#parents' => array('menu'),
    '#states' => array(
      'invisible' => array(
        'input[name="menu[enabled]"]' => array('checked' => FALSE),
370
      ),
371 372
    ),
  );
373

374
  // Populate the element with the link data.
375 376
  foreach (array('id', 'entity_id') as $key) {
    $form['menu']['link'][$key] = array('#type' => 'value', '#value' => $definition[$key]);
377
  }
378

379
  $form['menu']['link']['title'] = array(
380 381
    '#type' => 'textfield',
    '#title' => t('Menu link title'),
382
    '#default_value' => $definition['title'],
383
  );
384

385 386 387
  $form['menu']['link']['description'] = array(
    '#type' => 'textarea',
    '#title' => t('Description'),
388
    '#default_value' => $definition['description'],
389 390 391
    '#rows' => 1,
    '#description' => t('Shown when hovering over the menu link.'),
  );
392

393 394 395
  $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';
396

397
  $form['menu']['link']['weight'] = array(
398
    '#type' => 'number',
399
    '#title' => t('Weight'),
400
    '#default_value' => $definition['weight'],
401
    '#description' => t('Menu links with lower weights are displayed before links with higher weights.'),
402
  );
403 404
}

405
/**
406
 * Implements hook_node_submit().
407
 *
408
 * @see menu_ui_form_node_form_alter()
409
 */
410
function menu_ui_node_submit(EntityInterface $node, $form, FormStateInterface $form_state) {
411 412
  if (!$form_state->isValueEmpty('menu')) {
    $definition = $form_state->getValue('menu');
413 414 415 416 417
    if (empty($definition['enabled'])) {
      if ($definition['entity_id']) {
        $entity = entity_load('menu_link_content', $definition['entity_id']);
        $entity->delete();
      }
418
    }
419 420 421 422 423 424 425 426 427 428 429 430 431
    elseif (trim($definition['title']))  {
      // Decompose the selected menu parent option into 'menu_name' and 'parent',
      // if the form used the default parent selection widget.
      if (!empty($definition['menu_parent'])) {
        list($menu_name, $parent) = explode(':', $definition['menu_parent'], 2);
        $definition['menu_name'] = $menu_name;
        $definition['parent'] = $parent;
      }
      // @todo Figure out how to save this data without adding non-Field API
      //   properties to the node entity. https://www.drupal.org/node/2310173
      //   We have to tack this onto the node so we can save it later when we
      //   have a node ID for any new node.
      $node->menu = $definition;
432
    }
433 434 435
  }
}

436
/**
437 438
 * Implements hook_form_FORM_ID_alter().
 *
439
 * Adds menu options to the node type form.
440
 *
441
 * @see NodeTypeForm::form().
442
 * @see menu_ui_form_node_type_form_submit().
443
 */
444
function menu_ui_form_node_type_form_alter(&$form, FormStateInterface $form_state) {
445 446
  /** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */
  $menu_parent_selector = \Drupal::service('menu.parent_form_selector');
447
  $menu_options = menu_ui_get_menus();
448
  $type = $form_state['controller']->getEntity();
449 450 451 452 453 454
  if ($type->id()) {
    $config_values = \Drupal::config('menu.entity.node.' . $type->id())->get();
  }
  else {
    $config_values = array(
      'available_menus' => array('main'),
455
      'parent' => 'main:',
456 457
    );
  }
458
  $form['menu'] = array(
459
    '#type' => 'details',
460 461
    '#title' => t('Menu settings'),
    '#attached' => array(
462
      'library' => array('menu_ui/drupal.menu_ui.admin'),
463 464 465 466 467 468
    ),
    '#group' => 'additional_settings',
  );
  $form['menu']['menu_options'] = array(
    '#type' => 'checkboxes',
    '#title' => t('Available menus'),
469
    '#default_value' => $config_values['available_menus'],
470 471 472
    '#options' => $menu_options,
    '#description' => t('The menus available to place links in for this content type.'),
  );
473 474 475 476 477 478
  // @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.
  $options = $menu_parent_selector->getParentSelectOptions('');
479 480 481
  $form['menu']['menu_parent'] = array(
    '#type' => 'select',
    '#title' => t('Default parent item'),
482
    '#default_value' => $config_values['parent'],
483 484 485 486 487
    '#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')),
  );

488
  $form['actions']['submit']['#validate'][] = 'menu_ui_form_node_type_form_validate';
489
  $form['actions']['submit']['#submit'][] = 'menu_ui_form_node_type_form_submit';
490 491
}

492 493 494 495 496 497
/**
 * 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) {
498
  $available_menus = array_filter($form_state->getValue('menu_options'));
499 500 501
  // If there is at least one menu allowed, the selected item should be in
  // one of them.
  if (count($available_menus)) {
502
    $menu_item_id_parts = explode(':', $form_state->getValue('menu_parent'));
503 504 505 506 507
    if (!in_array($menu_item_id_parts[0], $available_menus)) {
      form_set_error('menu_parent', $form_state, t('The selected menu item is not under one of the selected menus.'));
    }
  }
  else {
508
    $form_state->setValue('menu_parent', '');
509 510 511
  }
}

512 513 514
/**
 * Submit handler for forms with menu options.
 *
515
 * @see menu_ui_form_node_type_form_alter().
516
 */
517
function menu_ui_form_node_type_form_submit(&$form, FormStateInterface $form_state) {
518 519
  $type = $form_state['controller']->getEntity();
  \Drupal::config('menu.entity.node.' . $type->id())
520 521
    ->set('available_menus', array_values(array_filter($form_state->getValue('menu_options'))))
    ->set('parent', $form_state->getValue('menu_parent'))
522
    ->save();
523 524
}

525 526 527 528 529 530
/**
 * Return an associative array of the custom menus names.
 *
 * @param $all
 *   If FALSE return only user-added menus, or if TRUE also include
 *   the menus defined by the system.
531 532
 *
 * @return array
533 534 535
 *   An array with the machine-readable names as the keys, and human-readable
 *   titles as the values.
 */
536
function menu_ui_get_menus($all = TRUE) {
537
  if ($custom_menus = entity_load_multiple('menu')) {
538 539 540 541
    if (!$all) {
      $custom_menus = array_diff_key($custom_menus, menu_list_system_menus());
    }
    foreach ($custom_menus as $menu_name => $menu) {
542
      $custom_menus[$menu_name] = $menu->label();
543 544
    }
    asort($custom_menus);
545
  }
546
  return $custom_menus;
547
}
548 549

/**
550
 * Implements hook_preprocess_HOOK() for block templates.
551
 */
552 553
function menu_ui_preprocess_block(&$variables) {
  if ($variables['configuration']['provider'] == 'menu_ui') {
554
    $variables['attributes']['role'] = 'navigation';
555 556
  }
}
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572


/**
 * 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.
      $menu = entity_load('menu', $menu_link->getMenuName());
      $breadcrumb[] = \Drupal::l($menu->label(), 'menu_ui.menu_edit', array('menu' => $menu->id()));
    }
  }
}