Drupal FAPI multistep errors on required fields

in drupal, error, fapi, multistep

One of the great usability features in the Drupal Form API are simple validators, such as #required. Just set it to true, and Drupal takes care of it. However, when in a multistep scenario, simple validators go haywire since moving to a different step validates the form. Normally, you cannot override form errors within your validation hook... but there's a workaround.

Simply put, when going backwards ( as in, to a previous step in our multistep form ), we need to clear all errors of the current step, since these will be evaluated in due time.

Run this snippet to clear all form errors and pass validation :

// Get the validation errors 
$errors = form_get_errors();

// Reset them  
form_set_error(null,'',true); 

// Get the error messages
$error_msgs = drupal_get_messages('error'); 

// NOTE:  Getting the messages clears them as well! Fix below

foreach($error_msgs['error'] as $error ) {
  // If the error message is not a form validation message, 
  //  set it again
  if(!in_array($error, $errors) ) { 
    drupal_set_message($error,'error');
  }
}

Just run it when you want to clear the validation messages. Error messages from other sources will be set again, since when getting drupal messages, they are deleted. 

Hope this helps some people, since most articles around suggest implementing form_alter or even more tedious hooks.

Cool image from Volacci