By YoshiN on
Hi all,
I'm trying to redirect each user to different URL after saving node, based on the submitted field value.
I have added textfield and custom submit handler in hook_form_alter():
function mymodule_form_alter(&$form, $form_state, $form_id) {
$form['my_field'] = array(
'#type' => 'textfield',
'#title' => 'My field',
'#size' => 30,
);
if ( !isset($form['#submit'])) $form['#submit'] = array();
$form['#submit'][] = 'my_submit_handler';
}
and here is my submit handler
function my_submit_handler($form, &$form_state){
if ( !empty($form_state['values']['my_field']) ) {
$form_state['redirect'] = 'page/1';
}
}
What I'm trying to do is if any value was entered in my_field, redirect to "page/1",
otherwise default destination(newly created node or ?destination=return/path if set).
But with the code above doesn't work, and I have found that $form_state['redirect'] is overwritten in node_form_submit() in node.module.
Cannot use drupal_goto() at this point as it will skip node_save() and things.
What's the best way to change the redirect destination?
Comments
found a solution.
Within the submit handler, changed value of
$_REQUEST['destination']instead of$form_state['redirect']and it worked:)Hi Yoshi, thanks for writing
Hi Yoshi, thanks for writing this and giving an explanation, spent HOURS wondering why it wasn't working, i figured it must be overridden somewhere else, but my limited Drupal knowledge was telling me that the submit handler should be the last callback...
The explanation
The explanation resides in https://api.drupal.org/api/drupal/core!lib!Drupal!Core!EventSubscriber!R... which overrides the form state defined redirection if the "destination" parameter is given in the URL (ie: /node/XXX/edit?destination=test).
See https://www.drupal.org/project/drupal/issues/2950883 for more insights.