Update entities programmatically

Last updated on
27 November 2017

To update an entity type programmatically, Please follow the following steps.

1. Check current entity status and make an image (Here get the ids list).
  Example :

$ids_old = \Drupal::entityQuery('entity_update_tests_cnt')->execute();

2. Update the correct entity type.
  Example :
 

$entity_type = \Drupal::entityTypeManager()->getStorage('entity_update_tests_cnt');
$result = EntityUpdate::safeUpdateMain($entity_type->getEntityType());

3. Check the new entity status and make an image.
  Example :

$ids_new = \Drupal::entityQuery('entity_update_tests_cnt')->execute();

4. Compare both status and determine update is success or failed.
  Example :

  if (!empty(array_diff($ids_old, $ids_new))) {
    // Your codes if update checking failed.
  }

Example

<?php

/**
 * @file
 * Entity update test module (entity_update_tests).
 *
 * This file provide install/uninstall/update tasks.
 */
use Drupal\Core\Utility\UpdateException;
use Drupal\entity_update\EntityUpdate;

/**
 * Update 01 - Example for update an entity type 'entity_update_tests_cnt'.
 */
function entity_update_tests_update_8001() {

  // Entity checking process : Get current entities list.
  $ids_old = \Drupal::entityQuery('entity_update_tests_cnt')->execute();

  // Get entity type.
  $entity_type = \Drupal::entityTypeManager()->getStorage('entity_update_tests_cnt');   
  // Make Update Using safeUpdateMain methode.
  if (!EntityUpdate::safeUpdateMain($entity_type->getEntityType())) {
    // Your codes if update failed.
    throw new UpdateException('Entity update failed.');
  }

  // Entity checking process : Compare with new list entities list.
  $ids_new = \Drupal::entityQuery('entity_update_tests_cnt')->execute();

  // Compare two lists.
  $result = array_diff($ids_old, $ids_new);
  if (!empty($result)) {
    // Your codes if update checking failed.
    throw new UpdateException('Entity update checking failed.');
  }

  return "Entity update success";
}

Module : Entity Update

Help improve this page

Page status: No known problems

You can: