Fragmented Thought

Drupal - Collapsible Form Item Descriptions

By

Published

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

emfluenceâ„¢ needed to start including fairly lengthy descriptions on some of their fields today, without taking all the screen real estate or bothering the users that already knew the system. The answer everyone agreed would be best would be to allow the form items to have collapsible descriptions. I traced out a way to do this by overriding the form_item theme provided by the basic form.inc from Drupal. This could be done through your template file, or a module by overriding the theme function (I explained this in another fragment a couple weeks ago) in case you're running multiple themes.

The following is a copy paste of the form.inc theme_form_item code, until you get to the description handling. It should be fairly readable, but I will point one thing out. Make sure you have some vague idea how many characters fit on a line! In our case, the ideal number was 130ish. If you make a collapsible item out of something that could fit on one line anyway you just add more processing from the server, and the client's javascript, while you gain nothing. Just let those one line descriptions drop right in, much better for everyone involved.

function custom_code_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'])) { if( strlen($element['#description']) <= 130 ){ // Original Method $output .= ' <div class="description">'. $element['#description'] ."</div>\n"; } else { // Collapsible Method $description = array( '#type' => 'fieldset' ,'#collapsible' => true ,'#collapsed' => true ,'#prefix' => ' <div class="description">' ,'#suffix' => ' </div>' ,'#title' => t($element['#title'] . ' Description') ,'text' => array( '#type' => 'markup' ,'#value' => '<div>' . $element['#description'] . '</div>' ) ); $output .= drupal_render($description); } } $output .= "</div>\n"; return $output; }