Skip to main content
Drupal: creating a dynamic link

We will create a dynamic link to display the “My orders” link in the user menu.

To create a link, we need to create a file: [MODULE MACHINE NAME].links.menu.yml

In this file, we will add:

[MODULE MACHINE NAME].user.orders:
  title: 'Mes commandes'
  weight: -10
  route_name: view.commerce_user_orders.order_page
  menu_name: account

view.commerce_user_orders.order_page represents the route to use, which requires the user parameter.
To pass this parameter dynamically, we will add a class:

[MODULE MACHINE NAME].user.orders:
  title: 'Mes commandes'
  weight: -10
  route_name: view.commerce_user_orders.order_page
  menu_name: account
  class: Drupal\[MODULE MACHINE NAME]\Plugin\Menu\OrdersMenuLink

OrdersMenuLink.php

<?php

namespace Drupal\hbk_souscription_pfna\Plugin\Menu;

use Drupal\Core\Menu\MenuLinkBase;

/**
 * Defines menu links provided by views.
 *
 * @see \Drupal\views\Plugin\Derivative\ViewsMenuLink
 */
class OrdersMenuLink extends MenuLinkBase {
  
  /**
   *
   * {@inheritdoc}
   * @see \Drupal\Core\Menu\MenuLinkInterface::getDescription()
   */
  public function getDescription() {
    return '';
  }
  
  /**
   *
   * {@inheritdoc}
   * @see \Drupal\Core\Menu\MenuLinkInterface::getTitle()
   */
  public function getTitle() {
    return $this->t('My orders');
  }
  
  public function getRouteParameters() {
    return [
      'user' => \Drupal::currentUser()->id()
    ];
  }
  
  /**
   *
   * {@inheritdoc}
   * @see \Drupal\Core\Menu\MenuLinkInterface::updateLink()
   */
  public function updateLink(array $new_definition_values, $persist) {
  }
}

 In this class, the getRouteParameters() method allows you to return the ID of the logged-in user.
 

Profile picture for user admin Stephane K

Écrit le

Il y'a 1 year
Modifié
Il y'a 2 weeks
Loading ...
WhatsApp
Support Habeuk : +237 694 900 622
WhatsApp Send