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
 * Script to delete all nodes in a Drupal site and reset auto-increment values.
 */

use Drupal\Core\Database\Database;

// Load all node IDs.
$node_ids = \Drupal::entityQuery('node')
  ->accessCheck(FALSE)
  ->execute();

// Delete all nodes.
if (!empty($node_ids)) {
  $node_storage = \Drupal::entityTypeManager()->getStorage('node');
  $nodes = $node_storage->loadMultiple($node_ids);
  $node_storage->delete($nodes);
}

// Reset AUTO_INCREMENT values for node-related tables.
$tables_to_reset = [
  'node',
  'node_revision',
  'node_field_data',
  'node_field_revision',
];

$database = Database::getConnection();

foreach ($tables_to_reset as $table) {
  $database->query("ALTER TABLE `{$table}` AUTO_INCREMENT = 1;");
}

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

Delete Paragraph Entities and Paragraph Library Items

<?php

/**
 * @file
 * Delete all Paragraph and Paragraphs Library entities.
 */

// Delete all Paragraphs.
$paragraph_ids = \Drupal::entityQuery('paragraph')
  ->accessCheck(FALSE)
  ->execute();

if (!empty($paragraph_ids)) {
  $paragraph_storage = \Drupal::entityTypeManager()->getStorage('paragraph');
  $paragraphs = $paragraph_storage->loadMultiple($paragraph_ids);
  $paragraph_storage->delete($paragraphs);
}

// Delete all Paragraph Library Items.
$library_ids = \Drupal::entityQuery('paragraphs_library_item')
  ->accessCheck(FALSE)
  ->execute();

if (!empty($library_ids)) {
  $library_storage = \Drupal::entityTypeManager()->getStorage('paragraphs_library_item');
  $items = $library_storage->loadMultiple($library_ids);
  $library_storage->delete($items);
}

// Reset AUTO_INCREMENT for paragraph-related tables.
$database = \Drupal::database();

$tables = [
  // Paragraphs.
  'paragraphs_item',
  'paragraphs_item_field_data',
  'paragraphs_item_revision',
  'paragraphs_item_revision_field_data',

  // Paragraph Library.
  'paragraphs_library_item',
  'paragraphs_library_item_field_data',
  'paragraphs_library_item_revision',
  'paragraphs_library_item_revision_field_data',
];

foreach ($tables as $table) {
  $database->query("ALTER TABLE `$table` AUTO_INCREMENT = 1;");
}

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

Also check this module: Preserve Changed Timestamp

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();
}