Handling redirects from a node submit

A common problem, and one that has tripped me up several times, is that when attempting to redirect from a node submission form via adding a submit handler in an implementation of hook_form_alter, the redirect instruction is never honored.

Take the following example, which is normally the appropriate way to handle adding a submission handler to a form:

<?php
// in your_module_hook_form_alter
$form['#submit'][] = 'your_module_custom_submit';
// end your_module_hook_form_alter

function your_module_custom_submit($form, &$form_state) {
 
// do something useful
 
$form_state['redirect'] = array('thank-you');
}
?>

For most forms the above will work fine, but if it is a node edit form, the user will never be taken to the 'thank-you' page and will instead always end up viewing the newly created/edited node.

The reason for this is that node_form_submit has a redirect hardcoded in it, and it will always execute after your submit handler.

The culprit lines are

<?php
 
if ($node->nid) {
   
$form_state['values']['nid'] = $node->nid;
   
$form_state['nid'] = $node->nid;
   
$form_state['redirect'] = 'node/' . $node->nid;
  }
?>

The way to get around this and redirect to a different page than the the node view after a node has been submitted is to add your submission handler to the submit button action:

<?php
// in your_module_hook_form_alter
  //$form['#submit'][] = 'your_module_custom_submit';  // this looks right, but won't work
 
$form['actions']['submit']['#submit'][] = 'your_module_custom_submit'// this will work, and your redirect in 'your_module_custom_submit' will trigger
// end your_module_hook_form_alter

function your_module_custom_submit($form, &$form_state) {
 
// do something useful
 
$form_state['redirect'] = array('thank-you');
}
?>

Tags: