Alter custom menu links with a session variable I've got a new problem, searched everywhere but was unable to find a solution.

I'm quite new to PHP / Drupal.

To explain :

I would like to use a session variable (got from a form) in my custom menu links, like this :

/path/{year}

So,in a module I have routes and links defined this way :

my_module.routing.yml :

testlink:
  path: '/path/{year}'
  defaults:
    _controller: '\Drupal\my_module\Controller\PageController::init'
    _title: 'Test'
    year: ''
  requirements:
    _permission: 'access content'


my_module.links.menu.yml :

testlink:
  title: 'test'
  description: 'test'
  parent: my-custom-menu
  menu_name: my-custom-menu
  route_name: testlink
  route_parameters: { year: '0000' }


Everything works fine, my menu link is displayed like this :

/path/0000

But I cannot find a way to use my session variable to replace "0000".

Any idea ?

Thanks in advance.
The menu links defined in yaml files are static. For dynamic menu links you have to use a menu link class:

src/Plugin/Menu/CustomMenuLink.php

&lt;?php

namespace Drupal\mymodule\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkDefault;
use Drupal\Core\Url;

/**
 * Custom Menu Link
 */
class CustomMenuLink extends MenuLinkDefault {

  public function getTitle() {
    return $this-&gt;t('Test-Link');
  }

  public function getRouteName() {
    return 'entity.node.canonical';
  }

  public function getRouteParameters() {
    $nid = rand(1,10);
    return ['node' =&gt; $nid];
  }

  public function getCacheMaxAge() {
    return 0;
  }

}


This example is a menu link randomly selected a node between 1 and 10. For code depending on a session replace the cache max age with a context:

  public function getCacheContexts() {
    return ['session'];
  }


Point the yaml file to this class to replace the static details of the route with the dynamic methods defined in the class:

mymodule.links.menu.yml

mymodule.testlink:
  weight: 10
  menu_name: main
  class: Drupal\mymodule\Plugin\Menu\CustomMenuLink