0

The main navigation menu in the site I am currently working on has a lot of menus. I want to hide the disabled ones.

I figured out that it is rendered via the menu_edit_form form.

entity.menu.edit_form:
  path: '/admin/structure/menu/manage/{menu}'
  defaults:
    _entity_form: 'menu.edit'
    _title_callback: '\Drupal\menu_ui\Controller\MenuController::menuTitle'
  requirements:
    _entity_access: 'menu.update'

I could not locate the menu edit form from the above entry. I am thinking of a doing form alter but is there a better way to alter the links shown in the form and also how do we locate the form that is used to display the link.

1 Answer 1

0

I figured out how to do this.

The form actually resides at

Drupal\menu_ui\MenuForm

As this is an entity form it has to be set/defined in the annotation of the ContentEntityType 'menu'. This is where the form class is usually linked with the 'menu.edit' found in the routing file _entity_form entry.

However I could not find such an annotation at first. Then I finally figured out where this is defined

/**
 * Implements hook_entity_type_build().
 */
function menu_ui_entity_type_build(array &$entity_types) {
  /** @var \Drupal\Core\Entity\EntityTypeInterface[] $entity_types */
  $entity_types['menu']
    ->setFormClass('add', 'Drupal\menu_ui\MenuForm')
    ->setFormClass('edit', 'Drupal\menu_ui\MenuForm')
    ->setFormClass('delete', 'Drupal\menu_ui\Form\MenuDeleteForm')
    ->setListBuilderClass('Drupal\menu_ui\MenuListBuilder')
    ->setLinkTemplate('add-form', '/admin/structure/menu/add')
    ->setLinkTemplate('delete-form', '/admin/structure/menu/manage/{menu}/delete')
    ->setLinkTemplate('edit-form', '/admin/structure/menu/manage/{menu}')
    ->setLinkTemplate('add-link-form', '/admin/structure/menu/manage/{menu}/add')
    ->setLinkTemplate('collection', '/admin/structure/menu');

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

The above was found in the menu_ui.module. So I learned today that there is alternative way to define the entity form.

So based on the above findings and to answer the question - to alter the Menu edit form links I did the following

  1. I proceeded to extend the MenuForm in my custom module
  2. I added a hook_entity_type_alter in my custom module where I linked the new form with the route.
/**
 * Implements hook_entity_type_alter().
 */
function my_custom_module_entity_type_alter(&$entity_types) {
  $entity_types['menu']
    ->setFormClass('edit', '\Drupal\my_custom_module\MyCustomMenuForm');
}

and voila I could get the new extended custom form in the url instead of the old one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.