drupaldrupal-8drupal-commercedrupal-navigation

Menu Token Drupal 8 alternative


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?


Solution

  • 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;
      }
    }