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, 2012 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, 2014 at 6:11
  • What happens here when the form is submitted with the checkbox unchecked but required set to true?
    – span
    Nov 18, 2017 at 17:27

3 Answers 3

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, 2021 at 18:54
0

If you want to checked all checkboxes values as default, you can use checked property in #attribute.

In your case:

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

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

This work for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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