Advanced Drupal form theming: Take control of error styling with a form-item-error class Jun. 10th, 2009 Todd Ross Nienkerk

Advanced Drupal form theming: Take control of error styling with a form-item-error class

June 10th, 2009

Note: This HOWTO covers Drupal 6.x.

By default, Drupal adds an .error class to the form element itself: textarea, select, input, and so on. Sometimes, that’s not good enough. Maybe a client needs the label‘s color changed — or a big, red border encompassing both the label and input elements.

This can be achieved by overriding theme_form_element() to add an error class to div.form-item, the div that wraps all elements in a form.

Add these lines to the top of your theme_form_element() override:

n”;
?>

The lines above should replace the following:

n”;
?>

All form elements except those listed in the $exempt_elements array will have two classes applied to div.form-item: .form-item-error and .form-item-error-ELEMENT_TYPE. Feel free to change these as you like.

Why are some elements exempt? Checkboxes and radio button usually come in groups of two or more wrapped inside a single div.form-item, and each individual box or button is wrapped in yet another div.form-item. This nesting can make theming difficult, so I’ve exempted them here. (You can, of course, customize this override to fit your needs.)

Here’s what the markup looked like before adding wrapping error classes. Note that the .error class is applied to the form elements themselves only, which makes theming some elements like radio buttons impossible in some browsers:

<

div class="form-item">

And here’s the same markup after applying the override above:

<

div class="form-item form-item-error form-item-error-radios">

<

div class="form-radios">

The wrapping .form-item divs now have error classes: form-item form-item-error form-item-error-textfield.

The technique described above was inspired by the function _form_set_class(), which is responsible for adding .required and .error classes to form elements.

Comments