Drupal Tips: Redirecting after Drupal form submission using form_state redirect without losing pagination and other query strings
The default behavior of drupal_redirect_form in Drupal 6 is to redirect the user to $_GET['q'] when an explicit redirect location is not set in $form_state['redirect']. So any form submission from a Drupal page with additional querystrings like in a paginated form (for example admin content listing forms or admin comment listing forms) will result in the querystrings being lost. This can be frustrating when you administer content from such forms as you have to click the pager link and go back to the previous page after form submission. This can easily be fixed by adding a submit handler for the form in question and setting form_state redirect correctly.
The example below was used to fix this issue for the comment administration form.
First the following submit handler is added for the form.
$form['#submit'][] = 'mymodule_comment_admin_overview_submit';
Then the function mymodule_comment_admin_overview_submit
is defined as follows to use set $form_state['redirect']
with the current URL with the query strings.
/**
* Custom submit handler for the comment_admin_overview form.
*/
function mymodule_comment_admin_overview_submit($form, &$form_state) {
$query = array();
// Use destination if it is already set.
if (isset($_REQUEST['destination'])) {
$path = $_REQUEST['destination'];
}
// If destination is not set then get the encoded querystrings from
the current URL after excluding q.
else {
$path = isset($_GET['q']) ? $_GET['q'] : '';
$qs = drupal_query_string_encode($_GET, array('q'));
$qsa = explode('&', $qs);
foreach ($qsa as $value) {
$q = explode('=', $value);
$query[$q[0]] = $q[1];
}
}
// Redirect the form to the same page from which it was submitted
without losing querystrings.
$form_state['redirect'] = array($path, $query);
}
Do note that $form_state['redirect']
is set with the URL in the form of an array which is then used by drupal_goto inside drupal_redirect_form.