5

Drupal 7 has drupal_goto() that would allow redirecting to an external url.

The change record indicated that ControllerBase::redirect is the method to be called in D8. https://www.drupal.org/node/2023537

This seems to work with internal drupal URLs but throws an error with external http urls -

[12-Nov-2014 21:00:22 Asia/Kolkata] Uncaught PHP Exception Symfony\Component\Routing\Exception\RouteNotFoundException: "Route "https://www.facebook.com/dialog/oaut....." does not exist." at /Applications/MAMP/htdocs/d8/core/lib/Drupal/Core/Routing/RouteProvider.php line 147

What would be the ideal equivalent of drupal_goto in D8 to redirect to an external URL?

18

With a route name on a Controller:

use Drupal\Core\Controller\ControllerBase;

class MyControllerClass extends ControllerBase {

  public function foo() {
    //...
    return $this->redirect('user.page');
  }
}

With a absolute url:

return new RedirectResponse('https://google.com');

On a form RedirectResponse doesn't work, then:

With a route name:

public function submitForm(array &$form, FormStateInterface $form_state) {
  //...

  $form_state->setRedirect('user.page');
}

With a absolute url:

public function submitForm(array &$form, FormStateInterface $form_state) {
  //...

  $form_state->setResponse(new TrustedRedirectResponse('https://google.com', 302));
  // You can change the response code from 302 to whatever you need
}
  • Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it. – Pupil Mar 7 at 13:10
1

return new RedirectResponse($absolute_url); seems to work

  • Redirects to external URLs are not allowed by default, use \Drupal\Core\Routing\TrustedRedirectResponse for it. – Pupil Mar 7 at 13:10

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.