0

I am trying to redirect users to a page on entity view. I am using RedirectResponse in hook_entity_view. But it is not redirecting to the desired page.

This is how I implemented this. After fetching my redirect url, I have passed it to RedirectResponse.

return new RedirectResponse($redirect_url);

Thank you

  • You should provide your code or some similar code sample. – Stefanos Petrakis Sep 20 '16 at 12:27
  • First, review the change log here: drupal.org/node/2023537. Second, post your code. Third, ensure the code is being hit by debugging it. – Kevin Sep 20 '16 at 13:21
  • 5
    Consider implementing a request event subscriber instead, you can then look for a certain route and e.g. node type and redirect there. That's the only correct way to set a redirect response, sending them yourself in arbitrary code is discouraged. – Berdir Sep 20 '16 at 20:07
3

After filling in the prompts with Drupal Console after executing drupal generate:event:subscriber, and entering kernel.request when prompted for the event name, it's possible to add something like the following to the callback function that handles the event:

use Symfony\Component\HttpFoundation\RedirectResponse;
...
 /**
   * This method is called whenever the kernel.request event is
   * dispatched.
   *
   * @param GetResponseEvent $event
   */
  public function kernelRequest(GetResponseEvent $event) {
    $request = $event->getRequest();
    $route_name = $request->attributes->get('_route');

    if ($route_name == 'entity.checkout.canonical') {

     // Create the destination URL, such as:
      $url = Url::fromRoute('user.register')->toString();

      // create redirect:
      $response = new RedirectResponse($url);
      $response->send();
    }
  }
2

Thank you, I got it working. Don't need to return the object of RedirectResponse. It works like this.

$response = new RedirectResponse($redirect_url);

$response->send();

It works this way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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