menu_ui.admin.es6.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. /**
  2. * @file
  3. * Menu UI admin behaviors.
  4. */
  5. (function($, Drupal) {
  6. /**
  7. *
  8. * @type {Drupal~behavior}
  9. */
  10. Drupal.behaviors.menuUiChangeParentItems = {
  11. attach(context, settings) {
  12. const $menu = $('#edit-menu').once('menu-parent');
  13. if ($menu.length) {
  14. // Update the list of available parent menu items to match the initial
  15. // available menus.
  16. Drupal.menuUiUpdateParentList();
  17. // Update list of available parent menu items.
  18. $menu.on('change', 'input', Drupal.menuUiUpdateParentList);
  19. }
  20. },
  21. };
  22. /**
  23. * Function to set the options of the menu parent item dropdown.
  24. */
  25. Drupal.menuUiUpdateParentList = function() {
  26. const $menu = $('#edit-menu');
  27. const values = [];
  28. $menu.find('input:checked').each(function() {
  29. // Get the names of all checked menus.
  30. values.push(Drupal.checkPlain($.trim($(this).val())));
  31. });
  32. $.ajax({
  33. url: `${window.location.protocol}//${window.location.host}${Drupal.url(
  34. 'admin/structure/menu/parents',
  35. )}`,
  36. type: 'POST',
  37. data: { 'menus[]': values },
  38. dataType: 'json',
  39. success(options) {
  40. const $select = $('#edit-menu-parent');
  41. // Save key of last selected element.
  42. const selected = $select.val();
  43. // Remove all existing options from dropdown.
  44. $select.children().remove();
  45. // Add new options to dropdown. Keep a count of options for testing later.
  46. let totalOptions = 0;
  47. Object.keys(options || {}).forEach(machineName => {
  48. $select.append(
  49. $(
  50. `<option ${
  51. machineName === selected ? ' selected="selected"' : ''
  52. }></option>`,
  53. )
  54. .val(machineName)
  55. .text(options[machineName]),
  56. );
  57. totalOptions++;
  58. });
  59. // Hide the parent options if there are no options for it.
  60. $select
  61. .closest('div')
  62. .toggle(totalOptions > 0)
  63. .attr('hidden', totalOptions === 0);
  64. },
  65. });
  66. };
  67. })(jQuery, Drupal);