0

What I need is to add menu item to some menu, but it should have different parameters (title and url) depending on language. So I created new module and added links.menu.yml like:

my_menu_item_id:
  title: 'Dummy Title'
  description: 'Dummy Description'
  url: http://www.google.com
  parent: mainmenu
  menu_name: mainmenu
  weight: -100

And item appears well. Then I added menu_links_discovered_alter hook like:

    function mymodule_menu_links_discovered_alter(&$links) {
      $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
      $links['my_menu_item_id']['title'] = 'Title:'.$language;
    }

And title really get's altered, but that renaming is cached. So when I visit some page in other language previous title remains until I clear the cache. How to solve this. How to make Drupal execute this code with every page instead of using cached value?

1 Answer 1

0

The discovery process is not the right place for dynamic behavior. A menu link defined statically in a yaml file can provide dynamic values only in a menu link plugin class.

In your case you would implement the method MenuLinkInterface::getTitle:

  public function getTitle() {
    return $title;
  }

See this answer https://drupal.stackexchange.com/a/249342/47547 for a complete example of a menu link class.

Although for translating the title this should not be necessary, titles of routes and menu links are covered by interface translation, see Translate routing and menu titles

2
  • Thank you 4k4, getTitle() override you suggested works. But how can I change url of menu item? I don't see any method that I can also override in that class.
    – MilanG
    Sep 11, 2018 at 11:51
  • override MenuLinkInterface::getUrlObject and return Url::fromUri('http://www.google.com');
    – 4uk4
    Sep 11, 2018 at 12:10

Your Answer

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

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