Skip to main content
Image
Drupal Sapiens snippet

Post Update in Drupal

An example where a POST UPDATE is implemented using hook hook_post_update_NAME()

Example code on how to use hook_post_update_NAME
/**
 * Implements hook_post_update_NAME().
 */
function MODULE_post_update_api_data_value(&$sandbox) {

  if (!isset($sandbox['total'])) {
  // Get API Data content type nid's.
    $nids = Drupal::entityQuery('node')
      ->condition('type', 'apidata')
      ->execute();
    $sandbox['total'] = count($nids);
    $sandbox['current'] = 0;
  }

  $nodes_per_batch = 50;
  $nids = Drupal::entityQuery('node')
    ->condition('type', 'apidata')
    ->range($sandbox['current'], $nodes_per_batch)
    ->execute();

  foreach ($nids as $nid) {
    $node = Drupal::entityTypeManager()
      ->getStorage('node')
      ->load($nid);

	// Check if the field is empty.
    if (empty($node->field_api_target->value)) {
      // If is empty, set default value (0).
      $node->field_api_target->value = 0;
    }

    $node->save();
    $sandbox['current']++;
  }

  if ($sandbox['total'] === 0) {
    // Until it is finished, the batch does not stop.
    $sandbox['#finished'] = 1;
  }
  else {
    // Indicates the percentage of the completed.
    $sandbox['#finished'] = ($sandbox['current'] / $sandbox['total']);
  }
}
Get list of previously executed post updates
drush eval '
$key_value = \Drupal::keyValue("post_update");
$update_list = $key_value->get("existing_updates");
print_r($update_list);
'

Join the Drupal Sapiens Community

Save content that interests you, connect with others in the community, contribute to win prizes and much more.

Login or create an account here

Featured

Last news