How to add a single on/off checkbox in a Drupal 6 admin form?

 

The short answer:

It’s not possible

The long answer:

In a simple user form it is possible to add a single on/off checkbox.

$form['thermometer_enabled'] = array(
'#type' => 'checkbox',
'#title' => t('Show the thermometer'),
'#options' => array(0 => t("no"), 1 => t("yes")),
);

But, it’s not possible to provide a default value (checked/unchecked) with a single chechbox. This causes difficulties when you want to show the saved value of a user.

A simple solution is to use a “yes/no radiobutton list” instead of a single checkbox.

$form['thermometer_enabled'] = array(
'#type' => 'radios',
'#title' => t('Show the thermometer'),
'#options' => array(0 => t("no"), 1 => t("yes")),
'#default_value' => variable_get('thermometer_enabled', 0),
);

In this example the result is saved in the variable thermomoeter_enabled and has the default value of 0 (false).

You May Also Like

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.