9th July 2012

How to have the 'true' option for a Boolean radio field output first in Drupal 7

Alli Price
Developer

If you use a Boolean field with radio buttons in Drupal 7, the false radio button outputs before the true. This became an annoyance to us whilst working on mega-sized forms, so here's our fix. To fix this you'll need to create a custom module, and implement the hook hook_field_widget_form_alter().

The following code assumes your module is called 'example'. All the code does is reverse the order of the options whilst preserving the keys, simple!


/**
* Implements hook_field_widget_form_alter().
*
* Have boolean fields output the true first.
*/
function example_field_widget_form_alter(&$element, &$form_state, $context) {
if ($context['field']['type'] == 'list_boolean' && isset($element['#options'])) {
$element['#options'] = array_reverse($element['#options'], TRUE);
}
}

That's it!