Skip to content

Instantly share code, notes, and snippets.

@DanLaufer
Last active April 3, 2022 19:57
Show Gist options
  • Save DanLaufer/64e164abe10f38ebad93ebd0d3df9945 to your computer and use it in GitHub Desktop.
Save DanLaufer/64e164abe10f38ebad93ebd0d3df9945 to your computer and use it in GitHub Desktop.
Drupal 8 - Programmatically Update Boolean Fields
<?php
// Single
use Drupal\node\Entity\Node;
$node = Node::load(1537);
$node->set('field_include_pop_up_form',0); // 0 to uncheck, 1 to check
$node->save();
drupal_set_message($node->get('field_include_pop_up_form')->value);
// Multiple
$query = \Drupal::entityQuery('node');
$rc_content_types = ['content_type_1'];
$field_boolean = 'field_bool';
$set_to = 1; // 0 to uncheck, 1 to check
$node_ids = $query
->condition('type', $rc_content_types, 'IN')
->condition('status', 1)
->execute();
$count_fixed = 0;
foreach($node_ids as $node_id) {
$node = \Drupal\node\Entity\Node::load($node_id);
if($node->hasField($field_boolean) && $node->get($field_boolean)->value != $set_to) {
//var_dump($node_id);
//var_dump($node->get($field_boolean)->value);
$node->set($field_boolean, $set_to);
$node->save();
$count_fixed++;
}
}
drupal_set_message($count_fixed);
// Mutliple nodes, conditionally on a field
// to run this on my local, `lando ssh` then `cat ./script.php | drush scr -`
// to run on a remote environment, `cat ./script.php | drush @mysite.live scr -`
$query = \Drupal::entityQuery('node');
$rc_content_types = ['my_content_type'];
$field_boolean = 'field_myfield';
print("Let's Begin\n");
$node_ids = $query
->condition('type', $rc_content_types, 'IN')
->condition('status', 1)
->execute();
$count_zero = 0;
$count_one = 0;
foreach($node_ids as $node_id) {
$node = \Drupal\node\Entity\Node::load($node_id);
if($node->hasField($field_boolean)) {
// matches criteria
if($node->hasField('field_asset_type') && $node->get('field_asset_type')->entity->getName() === 'Article') {
print($node_id . ' | ');
print("1 | ");
print("Asset Type: ");
print($node->get('field_asset_type')->entity->getName());
print("\n");
$node->set($field_boolean, 1);
$node->save();
$count_zero++;
// not matching criteria
} else {
print($node_id . ' | ');
print("0 | ");
print("Asset Type: ");
print($node->get('field_asset_type')->entity->getName());
print("\n");
$node->set($field_boolean, 0);
$node->save();
$count_one++;
}
}
}
print('Set to 0: ' . $count_zero . "\n");
print('Set to 1: ' . $count_one . "\n");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment