0

I have created 7 checkboxes using webform. I want the checkbox to be checked by default. For this I have used hook_form_alter() to change the checkbox as ticked by default. I have used 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. If I add another checkbox, I have to add another line of code. Is there a way to change the default value of all the checkboxes without to add a new line for every added checkbox?

2
  • Try this out. if ($form_id=='webform_client_form_31') { $element['submitted'][''][1]['#default_value'] = TRUE; } Sep 9 '15 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
    Jun 9 '17 at 21:24
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;
}

Your Answer

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