2

I'm working with the form API and I have a series of checkboxes. I need them to return true or false instead of 1 and 0.

$form['checkbox1'] = array(
    '#type' => 'checkbox',
    '#return_value' => 'true',
    '#title' => t('Checkbox title'),
    );

This works if the box is checked, but if it's left unchecked it still returns 0. Is there a way I can get an unchecked box to return false?

  • 1
    Is there any reason you want to get FALSE instead of 0? – kiamlaluno Nov 2 '16 at 21:05
4

It depends how you want to use the true/false value.

Case 1

You could change the data in a validation handler. In hook_form_alter, something like:

$form['#validate'][] = 'my_great_handler';

Then:

function my_great_handler($form, &form_state){
  $form_state['values']['checkbox1'][LANGUAGE_NONE][0]['value'] 
    = ($form_state['values']['checkbox1'][LANGUAGE_NONE][0]['value'] == 1);
}

Not sure what that would do for you, though.

Case 2

If you want to show users true/false rather than 1 or 0, you could change that in a template. Create a template for the field, and add something like:

Checkbox: <?php print $checkbox1 == 1 ? 'True' : 'False'; ?>

Case 3

If you want to save the data in a custom data store, you would add similar code right before the save, in hook_node_save, or some such.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.