4

I have a set of radio buttons. I first check the database to see if one of the options has already been set for the user and if so add it to $attending. If none have been set I don't want a default value. I thought I could achieve this by setting default_value to false. The problem I have is that when setting default_value to false and I submit the form without selecting an attending option, Drupal does not give me an error saying I didn't select an option for that radio group. How do I set a default value to nothing so that Drupal gives an error when I try to submit without selecting an option?

$form['attending'] = array(
  '#type' => 'radios',
  '#title' => t('Will you be attending?'),
  '#options' => array(
    '1'   => t('Yes'),
    '0' => t('No'),
  ),
  '#required' => TRUE,
  '#default_value' => isset($attending) ? $attending : false,
);
3

I'm not sure exactly why this happens; maybe FALSE is being cast to an integer in the validation, being evaluated as 0, and becoming an acceptable selection (your value for "No" being 0).

Fortunately you can use NULL instead:

'#default_value' => isset($attending) ? $attending : NULL
1
  • Thanks! That works. I don't know why I didn't try NULL before. May 23 '12 at 20:47

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.