0

I’m trying to redirect users in Drupal 8 as I was used to do in Drupal 7 with a simple drupal_goto().

This is my code.

$response = new \Symfony\Component\HttpFoundation\RedirectResponse(\Drupal::url($url_redirect));
$response->send();

Executing it, I get the following error:

Symfony\Component\Routing\Exception\RouteNotFoundException: Route http://mydomain.es/participar?utm_source=RTB&utm_campaign=&utm_medium=banner&utm_term=1 does not exist.

The alias /participar exists. What am I doing wrong?

  • Don't send the response, return it. – 4k4 Jun 22 '17 at 12:35
5

See drupal_goto() has been removed.

Drupal 8 (procedural)

use Symfony\Component\HttpFoundation\RedirectResponse;

function my_menu_callback_foo() {
  //....
  return new RedirectResponse(\Drupal::url('user.page'));
}

Drupal 8 (properly injected)

use Drupal\Core\Controller\ControllerBase;

class MyControllerClass extends ControllerBase {

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

If the route name is not known use RedirectResponse with a URL. When redirecting to an external location, use TrustedRedirectResponse.

use Drupal\Core\Controller\ControllerBase;

class MyControllerClass extends ControllerBase {

  public function foo() {
    //...
    return new TrustedRedirectResponse('https://example.com/some/path'); // for eg. Url::fromUserInput(\Drupal::destination()->get())->setAbsolute()->toString();
  }
}

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.