10

I have a custom form submit callback to redirect users to a specific page:

function MYMODULE_authfrontpageredirect_callback(array &$form, FormStateInterface &$form_state) {
  $url = \Drupal::service('path.validator')->getUrlIfValid('node/16');
  $form_state->setRedirect($url->getRouteName(), $url->getRouteParameters());
}

This works correctly unless the url has a destination query string, such as /node/add/mynode?destination=/user

In this case, the user will be redirected based on the query string (to /user) instead of my submit handler destination (node/16).

How do I forcibly override the destination query string content for this submit handler?

This question is similar to this D7 question but since Drupal 8 has the Symfony routing system the answers there did not help me.

2 Answers 2

19

To force a redirect remove the destination query string from the request:

\Drupal::request()->query->remove('destination');

After this you can also reset the RedirectDestination service, although this seems not to be necessary for a form:

\Drupal::destination()->set(NULL);

When you have already a URL object set it directly in $form_state:

$form_state->setRedirectUrl($url);

With the release of Drupal 10.2.0 you can use

$form_state->setIgnoreDestination();

See https://www.drupal.org/node/3375113

-1

Did you try using the RedirectResponse Class ? I have this kind of callbacks, and it removes URL parameters.

use Symfony\Component\HttpFoundation\RedirectResponse;

function MYMODULE_authfrontpageredirect_callback(array &$form, FormStateInterface &$form_state) {
  $response = new RedirectResponse(\Drupal::url('entity.node.canonical', ['node' => '16']));
  $response->send();
}
3
  • 4
    Sending a response is discouraged, see drupal.stackexchange.com/questions/215372/…
    – 4uk4
    Commented Nov 17, 2017 at 17:14
  • Did not know that, thank you ! Do you know why it is discouraged ? Commented Nov 18, 2017 at 17:48
  • 4
    Because the job of the Drupal kernel is to return a response, not to send one. Sending a response doesn't stop the code. This can have unexpected results, because Drupal continues building the response and doesn't know that you've already sent one.
    – 4uk4
    Commented Nov 18, 2017 at 20:52

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.