Super-flexible forms in Drupal 5

Feb
21
By Dan Kurtz | Filed Under: Drupal, theming

It's common practice for theme function writers to give every div a class, so that it can be targetted by CSS. For us, this is especially important in forms, since our clients often ask us to lay out forms in complicated ways.

This was a problem in Drupal 5 (and earlier). Although form elements had ids, so specific elements could be accessed from Javascript and CSS, they are all encased in wrapper divs with class "form-item". This means there's no easy way to lay out a specific form item.

It's been solved in the Drupal 6 version of theme_form_element() by adding unique ids to each form-item container. That's great, but what's better is that the new function works fine in Drupal 5. Just copy it into your template.php file and you've got easy-to-theme forms. Just goes to show how a minor code change can go a long way.

Here's the function:

<?php
function theme_form_element($element, $value) {
 
// This is also used in the installer, pre-database setup.
 
$t = get_t();

 
$output = '<div class="form-item"';
  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;
}
?>

No Comments

There are no comments for this entry. Why not be the first to post one?

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You may post code using <code>...</code> (generic) or <?php ... ?> (highlighted PHP) tags.

More information about formatting options