Customising the labels on radio-buttons

This blog post is more than 10 years old, so the content may be out of date.

Thought I'd quickly blog about this whilst this is fresh in my head!

Sometimes you want to add detail to a set of radio-buttons - e.g. you may want to show an example image below the radio-button's label:

Choose cable connection
( ) VGA
    [ pic of VGA cable ]

( ) DVI
    [ pic of DVI cable ]

( ) DisplayPort
    [ pic of DisplayPort cable ]

You would usually start with this Drupal code:

<?php
$form['cable_type'] = array(
  '#type' => 'radios',
  '#title' => t('Choose cable connection'),
  '#options' => array('vga' => t('VGA'),
                      'dvi' => t('DVI'),
                      'displayport' => t('DisplayPort'),
                     ),
  );

The problem is that you can add a #description property to the set of radio-buttons, but not to individual radio buttons.

The solution is to use an after-build handler to inject the description.

<?php
/**
 * Implementation of hook_form_alter().
 */
function foo_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'xxx_node_form') {
    // Add a custom after-build handler to the cable-type element.
    $form['cable_type']['#after_build'][] = '_foo_after_build';
  }
}
 
/**
 * After-build handler to add the example images to the inline/block element.
 */
function _foo_after_build($element, $form_state) {
  foreach(element_children($element['value']) as $key) {
    // Get the image-tag using a custom helper function.
    $desc = _foo_get_img($key);
    $element['value'][$key]['description'] = $desc;
  }
  return $element;
}

This can be used on normal FAPI elements, and on CCK radio-buttons, as shown by the form-alter above.

Comments

I’ve not too long ago started a blog, the knowledge you present on this website has helped me tremendously. Thanks for all your time & work.

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <apache>, <bash>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.