2

From what I understand the module 'GlobalRedirect' has been merged into the 'Redirect' module. So the redirect module should also redirect links as node/nid to it's url alias. When creating redirects trough the interface this works perfectly. But if I programatically do a redirect to a node/nid page it isn't being redirected to it's url alias.. Not sure if this is bad coding on my part, or feature not implemented in the module.

  /* @file EventSubscriber.php */

  public function onRequest(GetResponseEvent $event) {
    $baseUrl = $event->getRequest()->getBaseUrl();
    $attr = $event->getRequest()->attributes;
    if(null !== $attr && null !== $attr->get('node') && $attr->get('node')->get('type')->getString() == 'product_group' && 
    $attr->get('_controller') == '\Drupal\node\Controller\NodeViewController::view') {
      $node = $attr->get('node');
      $references = $node->get('field_references');
      $values = $references->referencedEntities();
      if($values){
        $nid = $values[0]->id();
        $language = \Drupal::languageManager()->getCurrentLanguage()->getId();
        $event->setResponse(new RedirectResponse($baseUrl. '/' . $language . '/node/' . $nid));
      }
  }

  static function getSubscribedEvents() {
    $events[KernelEvents::REQUEST][] = ['onRequest'];
    return $events;
  }

I'm using this code to redirect a product group to it's first referenced entity node, which uses automated url structure generated by a pathauto pattern, but the url alias isn't being shown after the redirect, it shows node/nid. I've verified that the url alias on that page actually works, and even added a redirect from that specific node/nid to it's url alias trough the interface, but no luck.

Am I doing something wrong? Is this working as intended? Is there a cleaner/better way for me to redirect? Still quite new to Drupal 8..

Using:
Drupal 8.1.3
Redirect 8.x-1.0-alpha1
Pathauto 8.x-1.0-alpha3

1 Answer 1

6

Try using Url.

$url = Url::fromRoute('entity.node.canonical', ['node' => $node->id()]);
new RedirectResponse($url->toString());
1
  • This did it, awesome thx!
    – Noedel
    Jun 24, 2016 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.