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

3
  • You should provide your code or some similar code sample. Commented Sep 20, 2016 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
    Commented Sep 20, 2016 at 13:21
  • 6
    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
    Commented Sep 20, 2016 at 20:07

2 Answers 2

6

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.

4

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();
    }
  }

Your Answer

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

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