Mean in green
I'm Kevin. I live in Salem, Mass with my wife and little boy and I build software.

Adding containers to Drupal form elements

Thursday Mar 19, 2009

So, I ran into an issue recently where I needed to add a container <div> to stylize my Drupal form elements. The issue was two-fold. One, I wanted to style form elements differently depending upon type, and two, I needed a container <div> that only wraps the form element and not the label.

Problem: I need a container around the <input> tag so that I can make the background of the input transparent, ditch the border then place a background image that is not attached to the <input> tag (there are scrolling issues in IE if the bg is set for the input tag). This way I can end up with a nice rounded input that matches the site theme.

This won't work for me:

Quick fix in template.php using theme_form_element() (Look for the line "ADD A CONTAINER DIV WITH A CLASS BASED UPON ELEMENT TYPE") <?php / implementation of theme_form_element(). / function mytheme_form_element($element, $value) { // This is also used in the installer, pre-database setup. $t = get_t();

$output = '

*' : '';

if (!empty($element['#title'])) { $title = $element['#title']; if (!empty($element['#id'])) { $output .= ' \n"; } else { $output .= ' \n"; } }


" . $value . "

if (!empty($element['#description'])) { $output .= '

'. $element['#description'] ."
\n"; }

$output .= "


return $output; }


Resulting HTML:

Above you can see the <div class="round-textfield"> wrapping my form element. Now, I am able to style the container div based upon which type of field it is!