Skip to content

Drupal Snippets

Warning: Never use these code on production!

These snippets can be run quickly via the command below:

drush php:script script_file.php

Delete All Entities

<?php

/**
 * @file
 * Delete all nodes code example.
 */

$ids = \Drupal::entityQuery('node')->execute();
$controller = \Drupal::entityTypeManager()->getStorage('node');
$entities = $controller->loadMultiple($ids);
$controller->delete($entities);

// Reset node table nid.
$database = \Drupal::database();
$queryresetincrement = "ALTER TABLE `node` AUTO_INCREMENT=1;";
$database->query($queryresetincrement);
$queryresetincrement = "ALTER TABLE `node_revision` AUTO_INCREMENT=1;";
$database->query($queryresetincrement);
$queryresetincrement = "ALTER TABLE `node_field_data` AUTO_INCREMENT=1;";
$database->query($queryresetincrement);
$queryresetincrement = "ALTER TABLE `node_field_revision` AUTO_INCREMENT=1;";
$database->query($queryresetincrement);

Reference:

  1. Delete all content entities in Drupal 8 - gist
  2. Reset the NID to zero after deleting all test content.
  3. Reset the NID to zero after deleting all test content. #comment-12740364

Term Creation (Published & Unpublished), Term Update, Set Parent for a Term

<?php

/**
 * @file
 * Taxonomy term creation example.
 */

use Drupal\taxonomy\Entity\Term;

// Taxonomy Vocabulary machine name vid.
$new_term = Term::create([
  'vid' => 'vocab_machine_name',
  'name' => 'vocab_term',
]);

$new_term->enforceIsNew();
$new_term->save();

/**
 * Unpublish newly created term.
 *
 * If you want the term to be unpublished,
 * you can set the term status to 0.
 */
$tid = $new_term->id();
$term = Term::load($tid);
$term->status->setValue('0');
$term->Save();

/**
 * Publish a term.
 *
 * If you want the term to be published,
 * you can set the term status to 1.
 */
// Can be any term id.
$tid = 23;
$term = Term::load($tid);
$term->status->setValue('1');
$term->Save();

/**
 * Set a parent for a term.
 *
 * In this example, the term with id 23 is the child term
 * And the term with id 79272 is the parent term.
 */
// Can be any term id.
$tid = 23;
// Parent term id. This can be any term id.
$parenttid = 79272;
$term = Term::load($tid);
$term->set('parent', $parenttid);
$term->Save();

Term and its Translations Creation

<?php

/**
 * @file
 * Taxonomy term and its translations creation example.
 */

use Drupal\taxonomy\Entity\Term;

// Taxonomy Vocabulary machine name vid.
$new_term = Term::create([
  'vid' => 'tags',
  'name' => 'test',
]);

// Greek translation.
$new_term->addTranslation('el', ['name' => 'testel']);
// Spanish translation.
$new_term->addTranslation('es', ['name' => 'testes']);
// French translation.
$new_term->addTranslation('fr', ['name' => 'testfr']);
// Turkish translation.
$new_term->addTranslation('tr', ['name' => 'testtr']);

$new_term->enforceIsNew();
$new_term->save();

Reference:

Add translation to a term or node programmatically in Drupal 8

Multi-value Field Update with Revisions

<?php

/**
 * @file
 * Multi-value Field Update with Revisions example.
 */

use Drupal\node\Entity\Node;

// Can be any user.
$user_id = 1;

// Node id to update.
$nid = 176440;
$node = Node::load($nid);
// The order of value array is the delta (0, 1, 2)
$node->field_multi_value_field = [3048, 3602, 3949];
$node->setNewRevision(TRUE);
$node->revision_log = 'Created revision for field_multi_value_field';
$node->setRevisionCreationTime(REQUEST_TIME);
$node->setRevisionUserId($user_id);
$node->save();

Update Entities without Creating Revisions and without Changing The Last Update Date

First, create a custom module that uses hook_node_presave and enable it.

<?php

/**
 * @file
 * Update nodes of a specific type.
 */

use Drupal\node\NodeInterface;

/**
 * Implements hook_ENTITY_TYPE_presave().
 */
function custom_module_node_presave(NodeInterface $node) {
  // Check if the node is of the correct type.
  if ($node->getType() == 'blog') {
    // Set the changed time to the original value.
    $node->setChangedTime($node->original->getChangedTime());
  }
}

Then you can run the following script.

<?php

/**
 * @file
 * Update nodes of a specific type.
 */

use Drupal\node\Entity\Node;

// Define the node type.
// Replace with your node type.
$node_type = 'blog';

// Get all nodes of the specific type.
$query = \Drupal::entityQuery('node')
  ->condition('type', $node_type)
// Bypass access checks.
  ->accessCheck(FALSE);

$nids = $query->execute();

// Loop through each node.
foreach ($nids as $nid) {
  // Load the node.
  $node = Node::load($nid);

  // Make changes to the node.
  // Replace TRUE with the value you want to set.
  // The example field is a boolean field.
  $node->set('field_to_update', TRUE);

  // Prevent the update time from being changed.
  $node->changed->setValue($node->getChangedTime());

  // Prevent a new revision from being created.
  $node->setNewRevision(FALSE);

  // Save the node.
  $node->save();
}