FAPI and Zebra Striping
I recently had to add "zebra striping" to a very long form generated with Drupal's Form API (FAPI). Fortunately, FAPI already wraps each element in a div with class "form-item", so I just needed to add a second class to each item that alternates between "odd" and "even". The easiest method to do this is simply implement a theme_form_element() theme hook.
Below is my implementation of the this hook in the "exampletheme" theme. To use this, simply rename to "yourthemename_form_element()" and put it into your theme's template.php file.
<?php
/**
* Implement theme_form_element().
*
* Here we are adding "zebra striping" to FAPI form elements.
*/
function exampletheme_form_element($element, $value) {
// NRD: The following three lines allow us to add zebra striping.
static $count = 0;
$count++;
$zebra = ($count % 2) ? 'odd' : 'even';
// This is also used in the installer, pre-database setup.
$t = get_t();
$output = '<div class="form-item '.$zebra.'"'; // NRD: Add zebra striping.
if (!empty($element['#id'])) {
$output .= ' id="'. $element['#id'] .'-wrapper"';
}
$output .= ">\n";
$required = !empty($element['#required']) ? '<span class="form-required" title="'. $t('This field is required.') .'">*</span>' : '';
if (!empty($element['#title'])) {
$title = $element['#title'];
if (!empty($element['#id'])) {
$output .= ' <label for="'. $element['#id'] .'">'. $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) ."</label>\n";
}
else {
$output .= ' <label>'. $t('!title: !required', array('!title' => filter_xss_admin($title), '!required' => $required)) ."</label>\n";
}
}
$output .= " $value\n";
if (!empty($element['#description'])) {
$output .= ' <div class="description">'. $element['#description'] ."</div>\n";
}
$output .= "</div>\n";
return $output;
}
?>To style this content, add something like the following to your theme's CSS:
/* Add zebra-striping to form items. */
div.fieldset-wrapper div.odd {
background-color: #eee;
padding: 2px 0 2px 0;
}