0

I have a content type that has a boolean field (checkbox) that editors need to always re-check on saving a new revision, if they want the value to still be true. Otherwise, it would be saved as false.

I'm using a hook_form_node_form_alter to modify the $form before the page is shown to the Editor.

public function my_module_form_node_form_alter(&$form, &$form_state, &$form_id) 
{
   $form['field_my_boolean_field']['#value'] = 0;
}

I've tried something similar to the above and have also tried #checked and #default_value in place of #value but nothing seems to work. The checkbox always renders checked (as it is saved in the database). How can I uncheck this boolean field when the form is rendered? Note that I do not want to change the actual value of the field for this node, just make it unchecked in the UI when the form for this content is shown.

1

You can use hook_ENTITY_TYPE_prepare_form() to change entity values before the entity form is built:

/**
 * Implements hook_ENTITY_TYPE_prepare_form() for Nodes.
 */
function mymodule_node_prepare_form(\Drupal\node\NodeInterface $node, $operation, \Drupal\Core\Form\FormStateInterface $form_state) {
  if ($node->getType() != 'my_content_type') {
    return;
  }
  if ($operation == 'edit') {
    $node->field_my_boolean_field->value = 0;
  }
}

This changes the value of the field for this node, but only temporary as long as the user doesn't submit the form.

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.