Bad example code for hook_menu_links_discovered_alter

Created on 2 February 2019, almost 6 years ago
Updated 19 May 2023, over 1 year ago

Problem/Motivation

From the API page documentation: https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Menu%21me...

function hook_menu_links_discovered_alter(&$links) {

  // Change the weight and title of the user.logout link.
  $links['user.logout']['weight'] = -10;
  $links['user.logout']['title'] = new \Drupal\Core\StringTranslation\TranslatableMarkup('Logout');

  // Conditionally add an additional link with a title that's not translated.
  if (\Drupal::moduleHandler()
    ->moduleExists('search')) {
    $links['menu.api.search'] = [
      'title' => \Drupal::config('system.site')
        ->get('name'),
      'route_name' => 'menu.api.search',
      'description' => new \Drupal\Core\StringTranslation\TranslatableMarkup('View popular search phrases for this site.'),
      'parent' => 'system.admin_reports',
    ];
  }
}

Above sample code provided in API page is a very bad example. You can't change the user.logout title using this code and second part of the code just crashes. For learners, it's a bit frustrating.

Proposed resolutions

  • Provide a valid working example for first part
  • Fix the crashing second part of the code

Remaining tasks

NA

API changes

NA

πŸ› Bug report
Status

Active

Version

10.1 ✨

Component
DocumentationΒ  β†’

Last updated about 7 hours ago

No maintainer
Created by

Live updates comments and jobs are added and updated live.
  • Needs manual testing

    The change/bugfix cannot be fully demonstrated by automated testing, and thus requires manual testing in a variety of environments.

Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • πŸ‡ΊπŸ‡ΈUnited States Amber Himes Matz Portland, OR USA

    This issue needs to be manually tested and verified. Also, unassigning it since the issue assignment happened 4 years ago.

  • πŸ‡³πŸ‡ΏNew Zealand luke.stewart

    The error generated is:
    Symfony\Component\Routing\Exception\RouteNotFoundException: Route "menu.api.search" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 206 of /web/core/lib/Drupal/Core/Routing/RouteProvider.php).

    Would it be a bad solution to just remove the second half of the example?

Production build 0.71.5 2024