menu_ui.module 19.1 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\Block\BlockPluginInterface;
14
use Drupal\Core\Link;
15
use Drupal\Core\Menu\MenuLinkInterface;
16
use Drupal\Core\Form\FormStateInterface;
17
use Drupal\Core\Routing\RouteMatchInterface;
18
use Drupal\menu_link_content\Entity\MenuLinkContent;
19
use Drupal\node\NodeTypeInterface;
20
use Drupal\system\Entity\Menu;
21
use Drupal\node\NodeInterface;
22

23
/**
24 25 26 27 28
 * Maximum length of menu name as entered by the user.
 *
 * @deprecated in Drupal 8.3.x and will be removed before Drupal 9.0.0. Use
 *   \Drupal\Core\Config\Entity\ConfigEntityStorage::MAX_ID_LENGTH because the
 *   menu name is a configuration entity ID.
29 30
 *
 * @see https://www.drupal.org/node/2831620
31
 */
32
const MENU_MAX_MENU_NAME_LENGTH_UI = 27;
33

34
/**
35
 * Implements hook_help().
36
 */
37
function menu_ui_help($route_name, RouteMatchInterface $route_match) {
38 39
  switch ($route_name) {
    case 'help.page.menu_ui':
40 41
      $output = '';
      $output .= '<h3>' . t('About') . '</h3>';
42
      $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>.', [':menu' => 'https://www.drupal.org/documentation/modules/menu/']) . '</p>';
43 44 45
      $output .= '<h3>' . t('Uses') . '</h3>';
      $output .= '<dl>';
      $output .= '<dt>' . t('Managing menus') . '</dt>';
46
      $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.', [':block_help' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('help.page', ['name' => 'block']) : '#', ':menu' => \Drupal::url('entity.menu.collection')]) . '</dd>';
47
      $output .= '<dt>' . t('Displaying menus') . '</dt>';
48
      $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>.', [':blocks' => (\Drupal::moduleHandler()->moduleExists('block')) ? \Drupal::url('block.admin_display') : '#', ':themes' => \Drupal::url('system.themes_page'), ':theme_settings' => \Drupal::url('system.theme_settings')]) . '</dd>';
49
      $output .= '</dl>';
50
      return $output;
51
  }
52
  if ($route_name == 'entity.menu.add_form' && \Drupal::moduleHandler()->moduleExists('block') && \Drupal::currentUser()->hasPermission('administer blocks')) {
53
    return '<p>' . t('You can enable the newly-created block for this menu on the <a href=":blocks">Block layout page</a>.', [':blocks' => \Drupal::url('block.admin_display')]) . '</p>';
54
  }
55
  elseif ($route_name == 'entity.menu.collection' && \Drupal::moduleHandler()->moduleExists('block') && \Drupal::currentUser()->hasPermission('administer blocks')) {
56
    return '<p>' . t('Each menu has a corresponding block that is managed on the <a href=":blocks">Block layout page</a>.', [':blocks' => \Drupal::url('block.admin_display')]) . '</p>';
57
  }
58 59
}

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

  if (isset($entity_types['node'])) {
    $entity_types['node']->addConstraint('MenuSettings', []);
  }
79 80
}

81
/**
82
 * Implements hook_block_view_BASE_BLOCK_ID_alter() for 'system_menu_block'.
83
 */
84
function menu_ui_block_view_system_menu_block_alter(array &$build, BlockPluginInterface $block) {
85 86
  if ($block->getBaseId() == 'system_menu_block') {
    $menu_name = $block->getDerivativeId();
87 88 89
    $build['#contextual_links']['menu'] = [
      'route_parameters' => ['menu' => $menu_name],
    ];
90 91 92
  }
}

93
/**
94 95 96 97 98 99
 * 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.
100
 */
101 102 103 104
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']);
105 106 107 108 109 110 111 112
    if ($entity->isTranslatable()) {
      if (!$entity->hasTranslation($node->language()->getId())) {
        $entity = $entity->addTranslation($node->language()->getId(), $entity->toArray());
      }
      else {
        $entity = $entity->getTranslation($node->language()->getId());
      }
    }
113 114 115
  }
  else {
    // Create a new menu_link_content entity.
116
    $entity = MenuLinkContent::create([
117
      'link' => ['uri' => 'entity:node/' . $node->id()],
118
      'langcode' => $node->language()->getId(),
119
    ]);
120
    $entity->enabled->value = 1;
121
  }
122 123 124 125 126 127
  $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();
128 129 130
}

/**
131 132 133 134 135 136 137
 * 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.
138
 */
139 140 141 142 143 144 145 146 147
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
148
    $type_menus = $node_type->getThirdPartySetting('menu_ui', 'available_menus', ['main']);
149
    if (in_array($menu_name, $type_menus)) {
150 151
      $query = \Drupal::entityQuery('menu_link_content')
        ->condition('link.uri', 'node/' . $node->id())
152 153 154 155
        ->condition('menu_name', $menu_name)
        ->sort('id', 'ASC')
        ->range(0, 1);
      $result = $query->execute();
156

157
      $id = (!empty($result)) ? reset($result) : FALSE;
158
    }
159 160
    // Check all allowed menus if a link does not exist in the default menu.
    if (!$id && !empty($type_menus)) {
161
      $query = \Drupal::entityQuery('menu_link_content')
162
        ->condition('link.uri', 'entity:node/' . $node->id())
163 164 165 166
        ->condition('menu_name', array_values($type_menus), 'IN')
        ->sort('id', 'ASC')
        ->range(0, 1);
      $result = $query->execute();
167

168 169 170 171
      $id = (!empty($result)) ? reset($result) : FALSE;
    }
    if ($id) {
      $menu_link = MenuLinkContent::load($id);
172
      $menu_link = \Drupal::service('entity.repository')->getTranslationFromContext($menu_link);
173
      $defaults = [
174 175 176
        'entity_id' => $menu_link->id(),
        'id' => $menu_link->getPluginId(),
        'title' => $menu_link->getTitle(),
177
        'title_max_length' => $menu_link->getFieldDefinitions()['title']->getSetting('max_length'),
178
        'description' => $menu_link->getDescription(),
179
        'description_max_length' => $menu_link->getFieldDefinitions()['description']->getSetting('max_length'),
180 181 182
        'menu_name' => $menu_link->getMenuName(),
        'parent' => $menu_link->getParentId(),
        'weight' => $menu_link->getWeight(),
183
      ];
184
    }
185
  }
186 187

  if (!$defaults) {
188 189 190 191
    // 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');
192
    $description_max_length = $field_definitions['description']->getSetting('max_length');
193
    $defaults = [
194 195 196
      'entity_id' => 0,
      'id' => '',
      'title' => '',
197
      'title_max_length' => $max_length,
198
      'description' => '',
199
      'description_max_length' => $description_max_length,
200 201 202
      'menu_name' => $menu_name,
      'parent' => '',
      'weight' => 0,
203
    ];
204 205
  }
  return $defaults;
206 207
}

208
/**
209
 * Implements hook_form_BASE_FORM_ID_alter() for \Drupal\node\NodeForm.
210 211 212
 *
 * Adds menu item fields to the node form.
 *
213
 * @see menu_ui_form_node_form_submit()
214
 */
215
function menu_ui_form_node_form_alter(&$form, FormStateInterface $form_state) {
216
  // Generate a list of possible parents (not including this link or descendants).
217
  // @todo This must be handled in a #process handler.
218
  $node = $form_state->getFormObject()->getEntity();
219
  $defaults = menu_ui_get_menu_link_defaults($node);
220 221
  /** @var \Drupal\node\NodeTypeInterface $node_type */
  $node_type = $node->type->entity;
222 223
  /** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */
  $menu_parent_selector = \Drupal::service('menu.parent_form_selector');
224 225 226 227 228 229
  $type_menus_ids = $node_type->getThirdPartySetting('menu_ui', 'available_menus', ['main']);
  if (empty($type_menus_ids)) {
    return;
  }
  /** @var \Drupal\system\MenuInterface[] $type_menus */
  $type_menus = Menu::loadMultiple($type_menus_ids);
230
  $available_menus = [];
231
  foreach ($type_menus as $menu) {
232
    $available_menus[$menu->id()] = $menu->label();
233
  }
234 235
  if ($defaults['id']) {
    $default = $defaults['menu_name'] . ':' . $defaults['parent'];
236 237
  }
  else {
238
    $default = $node_type->getThirdPartySetting('menu_ui', 'parent', 'main:');
239
  }
240
  $parent_element = $menu_parent_selector->parentSelectElement($default, $defaults['id'], $available_menus);
241
  // If no possible parent menu items were found, there is nothing to display.
242
  if (empty($parent_element)) {
243 244 245
    return;
  }

246
  $form['menu'] = [
247
    '#type' => 'details',
248
    '#title' => t('Menu settings'),
249
    '#access' => \Drupal::currentUser()->hasPermission('administer menu'),
250
    '#open' => (bool) $defaults['id'],
251
    '#group' => 'advanced',
252 253 254
    '#attached' => [
      'library' => ['menu_ui/drupal.menu_ui'],
    ],
255 256
    '#tree' => TRUE,
    '#weight' => -2,
257 258 259
    '#attributes' => ['class' => ['menu-link-form']],
  ];
  $form['menu']['enabled'] = [
260 261
    '#type' => 'checkbox',
    '#title' => t('Provide a menu link'),
262
    '#default_value' => (int) (bool) $defaults['id'],
263 264
  ];
  $form['menu']['link'] = [
265
    '#type' => 'container',
266 267 268 269 270 271 272
    '#parents' => ['menu'],
    '#states' => [
      'invisible' => [
        'input[name="menu[enabled]"]' => ['checked' => FALSE],
      ],
    ],
  ];
273

274
  // Populate the element with the link data.
275 276
  foreach (['id', 'entity_id'] as $key) {
    $form['menu']['link'][$key] = ['#type' => 'value', '#value' => $defaults[$key]];
277
  }
278

279
  $form['menu']['link']['title'] = [
280 281
    '#type' => 'textfield',
    '#title' => t('Menu link title'),
282
    '#default_value' => $defaults['title'],
283
    '#maxlength' => $defaults['title_max_length'],
284
  ];
285

286
  $form['menu']['link']['description'] = [
287
    '#type' => 'textfield',
288
    '#title' => t('Description'),
289
    '#default_value' => $defaults['description'],
290
    '#description' => t('Shown when hovering over the menu link.'),
291
    '#maxlength' => $defaults['description_max_length'],
292
  ];
293

294 295 296
  $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';
297

298
  $form['menu']['link']['weight'] = [
299
    '#type' => 'number',
300
    '#title' => t('Weight'),
301
    '#default_value' => $defaults['weight'],
302
    '#description' => t('Menu links with lower weights are displayed before links with higher weights.'),
303
  ];
304 305

  foreach (array_keys($form['actions']) as $action) {
306
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
307 308 309
      $form['actions'][$action]['#submit'][] = 'menu_ui_form_node_form_submit';
    }
  }
310 311 312 313 314 315 316 317 318

  $form['#entity_builders'][] = 'menu_ui_node_builder';
}

/**
 * Entity form builder to add the menu information to the node.
 */
function menu_ui_node_builder($entity_type, NodeInterface $entity, &$form, FormStateInterface $form_state) {
  $entity->menu = $form_state->getValue('menu');
319 320
}

321
/**
322
 * Form submission handler for menu item field on the node form.
323
 *
324
 * @see menu_ui_form_node_form_alter()
325
 */
326 327
function menu_ui_form_node_form_submit($form, FormStateInterface $form_state) {
  $node = $form_state->getFormObject()->getEntity();
328
  if (!$form_state->isValueEmpty('menu')) {
329 330 331 332
    $values = $form_state->getValue('menu');
    if (empty($values['enabled'])) {
      if ($values['entity_id']) {
        $entity = MenuLinkContent::load($values['entity_id']);
333 334
        $entity->delete();
      }
335
    }
336
    elseif (trim($values['title'])) {
337 338
      // Decompose the selected menu parent option into 'menu_name' and 'parent',
      // if the form used the default parent selection widget.
339 340 341 342
      if (!empty($values['menu_parent'])) {
        list($menu_name, $parent) = explode(':', $values['menu_parent'], 2);
        $values['menu_name'] = $menu_name;
        $values['parent'] = $parent;
343
      }
344
      _menu_ui_node_save($node, $values);
345
    }
346 347 348
  }
}

349
/**
350
 * Implements hook_form_FORM_ID_alter() for \Drupal\node\NodeTypeForm.
351
 *
352
 * Adds menu options to the node type form.
353
 *
354 355
 * @see NodeTypeForm::form()
 * @see menu_ui_form_node_type_form_submit()
356
 */
357
function menu_ui_form_node_type_form_alter(&$form, FormStateInterface $form_state) {
358 359
  /** @var \Drupal\Core\Menu\MenuParentFormSelectorInterface $menu_parent_selector */
  $menu_parent_selector = \Drupal::service('menu.parent_form_selector');
360
  $menu_options = menu_ui_get_menus();
361
  /** @var \Drupal\node\NodeTypeInterface $type */
362
  $type = $form_state->getFormObject()->getEntity();
363
  $form['menu'] = [
364
    '#type' => 'details',
365
    '#title' => t('Menu settings'),
366 367 368
    '#attached' => [
      'library' => ['menu_ui/drupal.menu_ui.admin'],
    ],
369
    '#group' => 'additional_settings',
370 371
  ];
  $form['menu']['menu_options'] = [
372 373
    '#type' => 'checkboxes',
    '#title' => t('Available menus'),
374
    '#default_value' => $type->getThirdPartySetting('menu_ui', 'available_menus', ['main']),
375 376
    '#options' => $menu_options,
    '#description' => t('The menus available to place links in for this content type.'),
377
  ];
378 379 380 381 382
  // @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.
383 384
  $options_cacheability = new CacheableMetadata();
  $options = $menu_parent_selector->getParentSelectOptions('', NULL, $options_cacheability);
385
  $form['menu']['menu_parent'] = [
386 387
    '#type' => 'select',
    '#title' => t('Default parent item'),
388
    '#default_value' => $type->getThirdPartySetting('menu_ui', 'parent', 'main:'),
389 390
    '#options' => $options,
    '#description' => t('Choose the menu item to be the default parent for a new link in the content authoring form.'),
391 392
    '#attributes' => ['class' => ['menu-title-select']],
  ];
393
  $options_cacheability->applyTo($form['menu']['menu_parent']);
394

395
  $form['#validate'][] = 'menu_ui_form_node_type_form_validate';
396
  $form['#entity_builders'][] = 'menu_ui_form_node_type_form_builder';
397 398
}

399
/**
400
 * Validate handler for forms with menu options.
401
 *
402
 * @see menu_ui_form_node_type_form_alter()
403 404
 */
function menu_ui_form_node_type_form_validate(&$form, FormStateInterface $form_state) {
405
  $available_menus = array_filter($form_state->getValue('menu_options'));
406 407 408
  // If there is at least one menu allowed, the selected item should be in
  // one of them.
  if (count($available_menus)) {
409
    $menu_item_id_parts = explode(':', $form_state->getValue('menu_parent'));
410
    if (!in_array($menu_item_id_parts[0], $available_menus)) {
411
      $form_state->setErrorByName('menu_parent', t('The selected menu item is not under one of the selected menus.'));
412 413 414
    }
  }
  else {
415
    $form_state->setValue('menu_parent', '');
416 417 418
  }
}

419
/**
420
 * Entity builder for the node type form with menu options.
421
 *
422
 * @see menu_ui_form_node_type_form_alter()
423
 */
424 425 426
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'));
427 428
}

429 430 431
/**
 * Return an associative array of the custom menus names.
 *
432 433 434
 * @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.
435 436
 *
 * @return array
437 438 439
 *   An array with the machine-readable names as the keys, and human-readable
 *   titles as the values.
 */
440
function menu_ui_get_menus($all = TRUE) {
441
  if ($custom_menus = Menu::loadMultiple()) {
442 443 444 445
    if (!$all) {
      $custom_menus = array_diff_key($custom_menus, menu_list_system_menus());
    }
    foreach ($custom_menus as $menu_name => $menu) {
446
      $custom_menus[$menu_name] = $menu->label();
447 448
    }
    asort($custom_menus);
449
  }
450
  return $custom_menus;
451
}
452 453

/**
454
 * Implements hook_preprocess_HOOK() for block templates.
455
 */
456 457
function menu_ui_preprocess_block(&$variables) {
  if ($variables['configuration']['provider'] == 'menu_ui') {
458
    $variables['attributes']['role'] = 'navigation';
459 460
  }
}
461 462 463 464

/**
 * Implements hook_system_breadcrumb_alter().
 */
465
function menu_ui_system_breadcrumb_alter(Breadcrumb &$breadcrumb, RouteMatchInterface $route_match, array $context) {
466 467 468 469 470
  // 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.
471
      $menu = Menu::load($menu_link->getMenuName());
472
      $breadcrumb->addLink(Link::createFromRoute($menu->label(), 'entity.menu.edit_form', ['menu' => $menu->id()]));
473 474 475
    }
  }
}