Monday, Apr 18th, 2011
Much of the styling and theming a designer specifies in a Drupal design mockup can be easily implemented. Once in a while, you'll run into a request that seems simple, but gets far more involved.
In this project, the design shows both the form field and label indicating when there is an error. The Drupal 7 default is to apply an "error" class to the <input> or <textarea> and to add a two pixel red border to the field. My design mockup shows a red <label> and a new background color for the field. Problem is, we also need an error indicating class on the label or wrapper field. I'm going to add it to the wrapper.
The field wrapper is generated in theme_form_element(). The error, for a text field, is detected and set in theme_textfield() using _form_set_class(). _form_set_class() checks for an error and adds the "error" class.
if (isset($element['#parents']) && form_get_error($element)) {
$element['#attributes']['class'][] = 'error';
}
We need to do the same thing for the label and/or wrapper.
Implementation
- Open your theme's template.php file.
- Search for a current implementation of theme_form_element(). It will be named [theme_name]_form_element().
- If it already exists, you'll need to be extra careful with your changes and skip 4-5.
- If it doesn't exist, copy/paste the original theme_form_element() from d.o. or directly from your includes/form.inc file.
- Change the function name from theme_form_element() to [theme_name]_form_element().
-
Locate the section of code that looks like this:
// Add a class for disabled elements to facilitate cross-browser styling. if (!empty($element['#attributes']['disabled'])) { $attributes['class'][] = 'form-disabled'; } $output = '<div' . drupal_attributes($attributes) . '>' . "\n";
Note that it is checking if the field is disabled, and adding a new form-disabled class to the <div>.
-
Add the field error checking code from _form_set_class() below the disabled check, and slightly modify it to work like this:
// Add a class for disabled elements to facilitate cross-browser styling. if (!empty($element['#attributes']['disabled'])) { $attributes['class'][] = 'form-disabled'; } if (isset($element['#parents']) && form_get_error($element)) { $attributes['class'][] = 'form-error'; } $output = '<div' . drupal_attributes($attributes) . '>' . "\n";
- Save template.php
- Clear your theme registry and check out your changes.
FYI: In my case, I needed to this with webform. The same type of change was made, but the theme_webform_element() function was replaced instead.
Comments
mulk replied on Permalink
Thank you so MUCH!
I'm working on a project with a webform and I want to do that (add error class on parent item). I search on the web and drupal site during some days...And found nothing.
Then I found your solution! Great.
(then I put your site in my bookmarks)
hbensalem replied on Permalink
thx you saved my day :)