Drupal - How to redirect to a page after submitting a form
In the submit handler you do
Drupal 7:
$form_state['redirect'] = 'url';
Drupal 8:
$form_state->setRedirect('route', $args, $options);
$form_state->setRedirectUrl(\Drupal\Core\Url);
It should be noted there are several triggers that may prevent a redirection:
$form_state['redirect'] === FALSE
: If set, the form builder function or form validation/submit handler does not want a user to be redirected, which means thatdrupal_goto()
is not invoked. For most forms, the redirection logic will be the same regardless of whether$form_state['redirect']
is undefined or FALSE. However, in case it was not defined and the current request contains a 'destination' query string,drupal_goto()
will redirect to that given destination instead. Only setting$form_state['redirect']
toFALSE
will prevent any redirection.$form_state['no_redirect'] === TRUE
: When set, the callback that originally built the form explicitly disallows any redirection, regardless of the redirection value in$form_state['redirect']
. For example,ajax_get_form()
defines$form_state['no_redirect']
when building a form in an AJAX callback to prevent any redirection.$form_state['no_redirect']
should NOT be altered by form builder functions or form validation/submit handlers.$form_state['programmed'] === TRUE
: means the form submission was usually invoked viadrupal_form_submit()
, so any redirection would break the script that invokeddrupal_form_submit()
.$form_state['rebuild'] === TRUE
: means the form needs to be rebuilt without redirection.
For Drupal 7, I tried this on a custom module and it works. It can also be used in a theme:
function my_theme_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'contact_site_form') {
$form['#submit'][] = 'contact_form_submit_handler';
}
}
function contact_form_submit_handler(&$form, &$form_state) {
$form_state['redirect'] = 'thank-you-page-alias';
}
BTW, I found this snippet here: https://gist.github.com/postrational/5768796