Multiple Checkboxes or Radio button descriptions

You, Drupal form APIDrupal
Back

If you are using the Drupal Form API you might know how to add a description to a form element, but when you use it in the same way like you do for the checkboxes it will only display one description for the whole checkboxes/radios set. But in many cases we need individual descriptions for grouped elements. If you are in D6 then you are out of luck but if you are in D7 then the functionality is there but hidden.

OKay, here is how you can make your checkboxes/radios 

in to 

Option 1: Using theme_preprocess_form_element()

Option 2: Using hook_form_alter()

Here is how you can use hook_form_alter().

// if your element is looks like this
$form\['ELEMENT\_NAME'\] = array(
  '#type' => 'radios',
  '#options' => array(
    'one' => 'One',
    'two' => 'Two',
    'three' => 'Three',
  ),
);

/\*\*
 \* Implements hook\_form\_alter()
 \*/
function YOUR\_MODULE\_form\_alter(&$form, &$form\_state, $form\_id) {
  // code goes here ...
  $options = $form\['ELEMENT\_NAME'\]\['#options'\];
  foreach ($options as $key => $option) {
    $form\['ELEMENT\_NAME'\]\[$key\]\['#description'\] = t('Individual element description');
  }
  // code goes here
}
© Heshan Wanigasooriya.RSS

🍪 This site does not track you.