Last Updated: February 25, 2016
·
3.43K
· tobiasdeardorff

Drupal 7 Hijack Form Errors

What I'm doing here is hijacking the form errors so that they don't display in the typical drupal message box and I can display them beside each field as desired.

//Hijack our errors so they don't display normally.
$errors = form_get_errors();
//Only rebuild form if there are actually errors that we need to display
if( !empty($errors) ) {
  $form_state['errors'] = $errors;
  $form_state['rebuild'] = TRUE;    
}
// Remove all error messages
drupal_get_messages('error');
// Get the array of errors and reset them
$errors = &drupal_static("form_set_error", array());
// Make sure that each error should be applied to the field
foreach (array_keys($errors) as $field) {
  unset($errors[$field]);
}

2 Responses
Add your response

Thanks for the wonderful tip. Just out of curiosity, where do you put the wonderful piece of code?

over 1 year ago ·

Hi soajetunmobi,

I'm using this code in the form_validate function for a custom form I built. If you build a form using the Form API you have the option of specifying a validate function and that is where I'm placing this code. If the form doesn't validate then it won't submit and you'll have the opportunity to display the error messages.

Hope that helps! Let me know if I can help any further.

Tobias

over 1 year ago ·