You are here

cshs_menu_link.module in Client-side Hierarchical Select 8

Client-side Hierarchical Select: Menu Link.

File

modules/cshs_menu_link/cshs_menu_link.module
View source
<?php

/**
 * @file
 * Client-side Hierarchical Select: Menu Link.
 */

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 *
 * @internal
 * @see \menu_ui_form_node_form_alter()
 */
function cshs_menu_link_form_node_form_alter(array &$form) : void {
  if (!empty($form['menu']['link']['menu_parent'])) {
    $element =& $form['menu']['link']['menu_parent'];
    $element['#type'] = 'cshs';
    $element['#attached']['library'][] = 'cshs_menu_link/cshs_menu_link';

    // The first item is always a menu name so the below processing
    // is relevant only if there is at least one link additionally.
    if (\count($element['#options']) > 1) {

      /* @var \Drupal\Core\Menu\MenuLinkManagerInterface $link_manager */
      $link_manager = \Drupal::service('plugin.manager.menu.link');
      foreach ($element['#options'] as $id => $label) {

        // Example `$id` values:
        // - `main:`;
        // - `main:standard.front_page`;
        // - `main:menu_link_content:d5517ae1-925f-4385-96a3-ceca5ad7bb61`.
        [
          $menu_name,
          $link_id,
        ] = \explode(':', $id, 2);

        // Assume there is no parent until we know that.
        $parent = '';
        if ($link = $link_manager
          ->getDefinition($link_id, FALSE)) {
          if (!empty($link['parent'])) {
            $parent = $menu_name . ':' . $link['parent'];
          }
        }
        else {
          \assert(FALSE, \sprintf('The link with ID "%s" must exist!', $link_id));
        }
        $element['#options'][$id] = [
          'name' => $label,
          'parent_tid' => $parent,
        ];
      }
    }
  }
}

/**
 * Implements hook_form_BASE_FORM_ID_alter().
 *
 * @internal
 * @see \taxonomy_menu_ui_form_taxonomy_term_form_alter()
 */
function cshs_menu_link_form_taxonomy_term_form_alter(array &$form) : void {
  if (\Drupal::moduleHandler()
    ->moduleExists('taxonomy_menu_ui')) {
    \cshs_menu_link_form_node_form_alter($form);
  }
}