You are here

function cshs_menu_link_form_node_form_alter in Client-side Hierarchical Select 8

Same name and namespace in other branches
  1. 8.2 modules/cshs_menu_link/cshs_menu_link.module \cshs_menu_link_form_node_form_alter()

Implements hook_form_BASE_FORM_ID_alter().

@internal

See also

\menu_ui_form_node_form_alter()

File

modules/cshs_menu_link/cshs_menu_link.module, line 14
Client-side Hierarchical Select: Menu Link.

Code

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,
        ];
      }
    }
  }
}