1

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.

5

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);
0

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();
}
  • 2
    Sending a response is discouraged, see drupal.stackexchange.com/questions/215372/… – 4k4 Nov 17 '17 at 17:14
  • Did not know that, thank you ! Do you know why it is discouraged ? – crtlf Nov 18 '17 at 17:48
  • 2
    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. – 4k4 Nov 18 '17 at 20:52
  • Seems logic. Thank's for the explanation ! – crtlf Nov 19 '17 at 21:40

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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