views:

55

answers:

2

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?

A: 

You could store the form data, if it's not big, in $_SESSION. Then check if it exists after the redirect.

I'm not familiar with Drupal, but you must be able to access the filtered form values. So instead of validating with the $_POST fields you validate with the stored $_SESSION values.

simplified example

session_start();

// ... Previous Validation

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

after redirecting

session_start();

$form_state = $_SESSION['form_state']);
unset($_SESSION['form_state']);

// The rest of the script....
gawpertron
In a custom PHP website your method would work. But, Drupal has it's own API for form handling. Really this is more of a Drupal question than a PHP or even form validation question.
Icode4food
A quick scan of the API doc and it mentions $form_state['values'] array which I guess is all your filtered form values, but you are right it doesn't seem, at first glance, a way of parsing anything other than $_POST. Why not store $form_state in the session and then pretend that a form has been validated and overwrite $form_state with the session values
gawpertron
+1  A: 

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.

googletorp