function MenuLinkContentHooks::entityPredelete

Implements hook_entity_predelete().

Attributes

#[Hook('entity_predelete')]

File

core/modules/menu_link_content/src/Hook/MenuLinkContentHooks.php, line 101

Class

MenuLinkContentHooks
Hook implementations for menu_link_content.

Namespace

Drupal\menu_link_content\Hook

Code

public function entityPredelete(EntityInterface $entity) : void {
  /** @var \Drupal\Core\Menu\MenuLinkManagerInterface $menu_link_manager */
  $menu_link_manager = \Drupal::service('plugin.manager.menu.link');
  $entity_type_id = $entity->getEntityTypeId();
  foreach ($entity->uriRelationships() as $rel) {
    $url = $entity->toUrl($rel);
    // Entities can provide uri relationships that are not routed, in this
    // case getRouteParameters() will throw an exception.
    if (!$url->isRouted()) {
      continue;
    }
    $route_parameters = $url->getRouteParameters();
    if (!isset($route_parameters[$entity_type_id])) {
      // Do not delete links which do not relate to this exact entity. For
      // example, "collection", "add-form", etc.
      continue;
    }
    // Delete all MenuLinkContent links that point to this entity route.
    $result = $menu_link_manager->loadLinksByRoute($url->getRouteName(), $route_parameters);
    if ($result) {
      foreach ($result as $id => $instance) {
        if ($instance->isDeletable() && str_starts_with($id, 'menu_link_content:')) {
          $instance->deleteLink();
        }
      }
    }
  }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.