Customising the labels on radio-buttons
This blog post is more than 2 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
appliance repai... (not verified)
May 4, 2011 - 1:33pm
Permalink
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