0

I have a "required" checkbox (single on-off boolean field) which users must check to agree to the rules of the site when they post a node of a certain content type. When users edit nodes of this content type, I would like to reset the checkbox to force them to check it again.

How can I do this in Drupal 7?

2 Answers 2

2

Implement hook_form_FORM_ID_alter() such that it clears the #default_value property of the widget:

function mymodule_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node_type = 'example_type'; // TODO: change to the desired node type
  $field = 'field_example';    // TODO: change to the name of the field

  $node = $form['#node'];
  if ($node->type == $node_type) {
    $language = $form[$field]['#language'];
    $form[$field][$language]['#default_value'] = 0;
  }
}
1
  • Nice solution! To me it creates a warning. I solved it by changing it like this: $form[$field][$language]['#default_value'] = array(0 => 0);
    – user14272
    Commented Mar 3, 2013 at 17:04
0

I can't comment on the other answer, but you can set a default value of an empty array (not 0 or FALSE to avoid a PHP warning):

$form[$field][$language]['#default_value'] = array();

See https://www.drupal.org/project/drupal/issues/3009881#comment-13407511

I would also add a condition to only set this default value on a node/add form, because #default_value will override any existing checked box and blank it out again on an edit form. I used:

if (!isset($node->nid) || isset($node->is_new)) {
  $form['field_mycheckbox'][LANGUAGE_NONE]['#default_value'] = array();
}

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.