Avoid Display of Empty Fieldsets

Last modified: May 17, 2009 - 00:29

Situation: I was creating a custom theme funciton for the user registration form. By default, Drupal displays the email and username fields within an "Account Information" fieldset on the user registration form. In my custom theme for this form, I don't want these two fields in a fieldset. Instead, I manually placed the username and email fields within my layout using the form_render function for each. Then, at the end of the custom theme function, I call form_render($form), to output the submit button and any remaining fields.

Problem: Because I have already "manually" placed all the fields belonging to the "Account Information" fieldset, this final call to form_render also renders an empty "Account Information" fieldset. I don't want this empty fieldset to be shown.

Proposed solution: Create an override of the theme_fieldset function that checks to see if the fieldset is empty before displaying it

How I achieved this:
1. I added the following entry to my template.php

/**
* Catch the theme_fieldset function, and redirect through the template api
*/
function phptemplate_fieldset($element) {
return _phptemplate_callback('fieldset',array('element' => $element));
}

2. I created a file named fieldset.tpl.php and placed it in the root directory of my theme. The contents of the file are basically the same as the theme_fieldset function, but with an initial "if" statement that checks to ensure that the fieldset is not empty.

<?php
 
//This override needed to avoid showing empty fieldsets...
  // All we do is add an initial "if" to the core theme_fieldset function to check that it's not empty
 
if ($element['#children']) {
      if (
$element['#collapsible']) {
       
drupal_add_js('misc/collapse.js');
   
       
$element['#attributes']['class'] .= ' collapsible';
        if (
$element['#collapsed']) {
        
$element['#attributes']['class'] .= ' collapsed';
        }
      }
   
      print
'<fieldset' . drupal_attributes($element['#attributes']) .'>' . ($element['#title'] ? '<legend>'. $element['#title'] .'</legend>' : '') . ($element['#description'] ? '<div class="description">'. $element['#description'] .'</div>' : '') . $element['#children'] . $element['#value'] . "</fieldset>\n";
  }
?>

 
 

Drupal is a registered trademark of Dries Buytaert.