0

I created 7 checkboxes which to be selected by default. To achieve this, I implemented hook_form_alter() using the following code.

function module_form_webform_client_form_31_after_build($element, &$form_state) {dpm($element);
  $element['submitted']['checkbox7'][1]['#checked'] = TRUE;
  $element['submitted']['checkbox6'][1]['#checked'] = TRUE;
  $element['submitted']['checkbox5'][1]['#checked'] = TRUE;
  $element['submitted']['checkbox4'][1]['#checked'] = TRUE;
  $element['submitted']['checkbox3'][1]['#checked'] = TRUE;
  $element['submitted']['checkbox2'][1]['#checked'] = TRUE;
  $element['submitted']['checkbox1'][1]['#checked'] = TRUE;

  return $element;
}

This code works fine for me.

Is there a way to change the default value of all the checkboxes without adding a new line for each new checkbox I could later add?

2
  • Try this out. if ($form_id=='webform_client_form_31') { $element['submitted'][''][1]['#default_value'] = TRUE; } Commented Sep 9, 2015 at 8:58
  • This is a wild guess. How do you expect it to work? For Drupal $element['submitted'][''] doesn't mean all the checkbox elements in the form.
    – apaderno
    Commented Jun 9, 2017 at 21:24

2 Answers 2

1

This code find the checkboxes in the 'submitted' element and check it by default. If you make a screenshot of dsm($element['submitted']) message I can check if this code is correct ^^

function module_form_webform_client_form_31_after_build($element, &$form_state) {
  foreach ($element['submitted'] as $key => &$value) {
    if ( $value['#type'] == 'checkbox' ) {
      $element['submitted'][$key][1]['#checked'] = TRUE;
    }
  }
  return $element;
}
0

Can you try the following code?

function module_form_webform_client_form_31_after_build($element, &$form_state) {
  foreach ($element['submitted'] as $key => &$value) {
    if (strpos($key, 'checkbox')) {
      $value[1]['#checked'] = TRUE;
    }
  }
  return $element;
}