0

I am currently on the process of moving a large Drupal commerce website from drupal 7 to drupal 8.

One of the biggest issues I have come up against so far is the lack of D8 versions of well used modules, the main one being Menu Token.

I need this to create a custom menu in the User account area of the website with links to orders. I need to beable to include the current user ID in the url:

user/user id/orders

Is there a way of doing this without the Menu Token module?

apaderno
  • 28,547
  • 16
  • 75
  • 90
Sean Lang
  • 422
  • 3
  • 6
  • 22

1 Answers1

2

One way to deal with it, until the menu token module is ready for 8 is to make the redirect yourself. You can do that by implementing an EventSubscriber. This makes it possible to make the token replacement and redirect the response - ie if your menu path is /user/{user}/orders you replace {user} with current user id and redirect the response.

Your event subscriber could look something like this:

namespace Drupal\YOUR_MODULENAME\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;


class RedirectRequestEventSubscriber implements EventSubscriberInterface {

  public function checkUserUidRedirection(GetResponseEvent $event) {
    if (\Drupal::currentUser()->isAnonymous()) {
      return;
    }
    $request_uri = urldecode(\Drupal::request()->getRequestUri());
    if (preg_match('/\{user\}/', $request_uri)) {
      $current_user = \Drupal::currentUser()->id();
      $request_uri = preg_replace('/\{user\}/', $current_user, $request_uri);
      $response = new RedirectResponse($request_uri, 301);
      $response->send();
    }
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = array('checkUserUidRedirection');
    return $events;
  }
}
topstash
  • 98
  • 9
  • This works for me once, but then I click on the link again and it doesn't pick it up. I'm on Drupal 9.2, so I don't know if something has changed or if this is some kind of caching thing or what? Any ideas? – Delford Chaffin Oct 14 '21 at 19:54