18

How do I show a checkboxes form element that is selected by default?

I tried setting #default_value as in the following code, but it doesn't work.

$form['ios'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#default_value' => 'checked',
); 

Is #default_value the wrong attribute?

3
  • Have you tried this? $form['ios'] = array('#type' => 'checkboxes', '#options' => $options, '#default_value' => array($value)); $value should be the option you want selected by default. Sep 13 '12 at 12:02
  • If you have a single field, you can use the following code. $form['name']['terms_condition'] = array( '#type' =>'checkbox', '#title'=>t('Terms and conditions'), '#required'=>TRUE, '#default_value' =>TRUE);
    – shashik493
    Dec 4 '14 at 6:11
  • What happens here when the form is submitted with the checkbox unchecked but required set to true?
    – span
    Nov 18 '17 at 17:27
25

#default_value for checkboxes form elements should be set as in the following code.

$options = array();
$options["1"] = "One";
$options["2"] = "Two";
$options["3"] = "Three";
$options["4"] = "Four";

$form['ios'] = array(
  '#type' => 'checkboxes',
  '#options' => $options,
  '#default_value' => array("1", "2", "3")
);
0
0

You have to give "#default_value" all $options keys

In your case:

$form['ios']['#default_value'] =  array_keys($form['ios']['#options']); 
1
  • It depends on what selected means for the OP, but to me it means at least one checkbox is selected. Since the OP already accepted an answer, I take he didn't mean that all the checkboxes needed to be selected.
    – apaderno
    Jun 24 at 18:54

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.