Skip to main content

Drupal 9: How to alter dynamically the url of a menu link

This is a snippet on how to change dynamically the URL link of a menu item. For this case i want the user that is logged in to have access to the node edit form of the menu item with the text "unique m_item". In the table after  of the code you can find examples of how to show the node view, edit, delete etc  routes instead of the node edit form page route.

use Drupal\Core\Url;

function pixelthis_link_alter(&$variables) {
  if (stripos($variables['text'], 'unique m_item') !== false) {
    $uid = \Drupal::currentUser()->id();
    $query = \Drupal::entityQuery('node')
        ->condition('type', 'node_bundle_name')
        ->condition('status', 1)
        ->condition('field_user_ref.target_id', $uid)
        ->sort('created', 'DESC');
    $result = $query->execute();
    if ($result){
      $nid = array_pop($result);
      //This is for showing the node edit form of the node
      $new_edit_url = Url::fromRoute('entity.node.edit_form', ['node' => $nid]);
      $variables['url'] = $new_edit_url;
    }
  }
}

Here you can find some other possible node route links

Links Key Route Name Route Example URI Description
canonical entity.node.canonical /node/1 View a specific node
add-page entity.node.add_page /node/add Select bundle of node to be added
add-form entity.node.add_form /node/add/article Add a node (of a specific bundle)
edit-form entity.node.edit_form /node/1/edit Edit form for a specific node
delete-form entity.node.delete_form /node/1/delete Delete form for a specific node
collection entity.node.collection /admin/content View all nodes as a list

From https://www.drupal.org/docs/drupal-apis/entity-api/introduction-to-enti…

hook_link_alter