Can I set a form_state redirect with a destination parameter in form submission?

Mark B picture Mark B · Nov 10, 2010 · Viewed 9.4k times · Source

I've built a "Quick Links" drop-down select box for my Drupal-based web app. The select box is implemented as a standard Drupal form, which appears on all pages in the site. When the user selects an option and submits the form, I want to redirect the user to the appropriate page, but have them return to the original page when they have finished.

e.g. user is on node/5, and selects a quick link which takes them to another form. When they have completed this form, I want them to be returned to node/5.

I have achieved this in other parts of the system using drupal_get_destination to append the ?destination=node/5 querystring parameter to the destination form, and this works nicely. However, in my quicklinks form submit handler, I'm setting form_state['redirect'] to set the target page, and if I add the ?destination= parameter it gets URL-encoded, and so isn't picked up when my target form is submitted.

function dh_seo_quick_links_form_submit($form, &$form_state) {
  $form_state['redirect'] = $form['#link_targets'][$link].'?'.drupal_get_destination();
}

Have I gone about this completely the wrong way? Is this redirection even possible? Could I do something clever with the $_REQUEST variables directly?

Answer

James Andrews picture James Andrews · Feb 20, 2013

Here's a nice solution for Drupal 7 which allows you to use relative paths:

$form_state['redirect'] = array(
  'node/[node number]',
  array(
    'query' => array(
      'variable_name' => 'value',
    ),
    'fragment' => 'hash_fragment'
  ),    
);

This code creates the following url:

..?node/[node number]&variable_name=value#hash_fragment

This allows you a lot of flexibility while taking advantage of the Drupal framework.