Search code examples
phpdrupalhttp-redirectdrupal-fapidrupal-forms

Redirect form in validation fail


I have a situation that if my form doesn't validate I need it to remove all but the first argument from the url. The reason for this is because the results of my form are displayed below the form in the content area. If the form doesn't validate I need to remove any previous results.

I am have tried the following in my form_validate function.

// Check if there were any errors.
$errors = form_set_error();
if (!empty($errors)) {
  drupal_goto(arg(0));
}

The destination page obviously is the same except that all arguments, except the first, are stripped. The problem is that Drupal forgets about the previous form state and the errors that were raised by the form_validate function.

I have also tried to change the #redirect value in my form_validate function but to no avail.

Any suggestions?


Solution

  • You have put yourself in a bad situation. AFAIK, you can't redirect without loosing the $form_state. Redirecting wont work unless the form is submitted, so as long as the form doesn't validate you wont get far.

    I don't know how you setup your code, but I seems to me that you will have better luck settings a variable in the $form_state and using that to determine if you should hide/display the results.

    An alternative option would be to save the $form_state in the global $_SESSION['batch_form_state'], to have it used when the form is initiated. I haven't tried it before and it's a bit hackish, but it should work.