Adding IDs to all Fieldsets

A themer on a project I was recently working on needed a lot of CSS IDs added to fieldsets throughout the site.

Fortunately, there's a theme_fieldset() function in includes/forms.inc

I was able to copy that function into the phptemplate.php file, obviously change theme_ to phptempalte_ in the function name, and then add logic that adds an ID based on the fieldset name if an id does not already exist.

Here's the code:

/**
* Format a group of form items.
*
* @param $element
*   An associative array containing the properties of the element.
*   Properties used: attributes, title, value, description, children, collapsible, collapsed
* @return
*   A themed HTML string representing the form item group.
*
* @ingroup themeable
*/
function phptemplate_fieldset($element) {
  if (!empty($element['#collapsible'])) {
    drupal_add_js('misc/collapse.js');

    if (!isset($element['#attributes']['class'])) {
      $element['#attributes']['class'] = '';
    }

    $element['#attributes']['class'] .= ' collapsible';
    if (!empty($element['#collapsed'])) {
      $element['#attributes']['class'] .= ' collapsed';
    }
  }

  if (empty($element['#attributes']['id'])) {
    $element['#attributes']['id'] = form_clean_id($element['#title']);
  }

  return '<fieldset'. drupal_attributes($element['#attributes']) .'>'. ($element['#title'] ? '<legend>'. $element['#title'] .'</legend>' : '') . (isset($element['#description']) && $element['#description'] ? '<div class="description">'. $element['#description'] .'</div>' : '') . (!empty($element['#children']) ? $element['#children'] : '') . (isset($element['#value']) ? $element['#value'] : '') ."</fieldset>\n";
}