2

This question already has an answer here:

I have a note type 'team' with a body field and a checkbox field (checked by default). I want to automatically check the box on save IF there is content in the body field. Is there a way to do that programmatically?

marked as duplicate by No Sssweat, Pierre.Vriens, DRUPWAY, kiamlaluno May 2 '18 at 14:38

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • There are cross-overs between the questions, but mine was specific to conditionally updating the value of a field based on the value of another field, not just updating a single field. – erier May 2 '18 at 16:51
7

Yes, this is possible with hook_ENTITY_TYPE_presave

/**
 * Auto check checkbox whatever, etc, etc.
 *
 * Implements hook_ENTITY_TYPE_presave()
 */
function my_module_node_presave($entity) {
  if ($entity->bundle() == 'team') {
    // Check if there is content in the body field.
    if (!empty($entity->body->value)) {
      // Set checkbox field.
      $entity->set('my_checkbox_field', 1);
    }
  }
}

Then, you'll probably want to remove the checkbox field from your form display on the Manage Form Display screen and also update the field settings so it's not checked by default since you'll be programmatically checking it if your body field has a value.

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