-
-
Save gargsuchi/395161dd410671ab2893fe2d006cfb99 to your computer and use it in GitHub Desktop.
Drupal 8 - Programmatically Update Boolean Fields
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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