You are here

special_menu_items.module in Special menu items 8

File

special_menu_items.module
View source
<?php

use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Template\Attribute;

/**
 * Implements hook_entity_type_build().
 */
function special_menu_items_entity_type_build(array &$entity_types) {
  if (isset($entity_types['menu_link_content'])) {
    $entity_types['menu_link_content']
      ->set('originalClass', 'Drupal\\menu_link_content\\Entity\\MenuLinkContent');
    $entity_types['menu_link_content']
      ->setClass('Drupal\\special_menu_items\\MenuLinkContent');
  }
}

/**
 * Implements hook_entity_base_field_info_alter().
 */
function special_menu_items_entity_base_field_info_alter(&$fields, EntityTypeInterface $entity_type) {
  if ($entity_type
    ->id() == 'menu_link_content') {
    $fields['link']
      ->setRequired(FALSE);
  }
}

/**
 * Implements hook_preprocess_HOOK().
 */
function special_menu_items_preprocess_table__menu_overview(&$variables) {
  foreach ($variables['rows'] as &$row) {
    if ($url = $row['cells'][0]['content'][1]['#url']) {
      if ($url
        ->isRouted() && !$url
        ->getRouteName()) {
        $title = $row['cells'][0]['content'][1]['#title'];
        $row['cells'][0]['content'][1] = array(
          '#markup' => $title,
        );
      }
    }
  }
}

/**
 * Implementation of hook_preprocess_HOOK().
 */
function special_menu_items_preprocess_menu(&$variables) {
  foreach ($variables['items'] as $menu_link_key => &$menu_link) {
    special_menu_items_preprocess_menu_link($menu_link);
  }
}

/**
 * Recursive menu_link item fixer.
 */
function special_menu_items_preprocess_menu_link(&$menu_link) {
  if ($menu_link['url']
    ->isRouted() && !$menu_link['url']
    ->getRouteName()) {
    $menu_link['no_link'] = TRUE;

    // Copy the old attributes, not to happy about this, because our module get's called before the theme layer.
    $attributes = $menu_link['url']
      ->getOption('attributes');
    $attributes['class'][] = 'no-link';

    // Create a new attribute object to sent to the twig layer.
    $menu_link['no_link_attributes'] = new Attribute($attributes);
  }
  if (isset($menu_link['below']) && count($menu_link['below'])) {
    foreach ($menu_link['below'] as &$child_menu_link) {
      special_menu_items_preprocess_menu_link($child_menu_link);
    }
  }
}