Using update hook with big queries

Public

This is an example how to use "queue" during the update process. This code snippet updates a field's value in each node but handles only 10 nodes per run to avoid the exceed of execute time limit or other server limitations.

Get raw version
php
  1. /**
  2.  * Enable trips' summary_accomodation field by default.
  3.  */
  4. function ikaland_core_update_7001(&$sandbox) {
  5. $disabled_nids = array(679, 677, 672, 525, 138, 136, 707, 712, 550, 127);
  6. if (empty($sandbox['total'])) {
  7. $sandbox['progress'] = 0;
  8. $sandbox['last_nid'] = 0;
  9.  
  10.  
  11. // Count the total number of the trip nodes.
  12. $query = new EntityFieldQuery();
  13. $query->entityCondition('entity_type', 'node')
  14. ->entityCondition('bundle', 'trip')
  15. ->propertyCondition('nid', $disabled_nids, 'NOT IN')
  16. ->count();
  17. $sandbox['total'] = $query->execute();
  18. }
  19.  
  20. // Get the next 10 trip node.
  21. $query = new EntityFieldQuery();
  22. $query->entityCondition('entity_type', 'node')
  23. ->entityCondition('bundle', 'trip')
  24. ->propertyCondition('nid', $disabled_nids, 'NOT IN')
  25. ->propertyCondition('nid', $sandbox['last_nid'], '>')
  26. ->propertyOrderBy('nid')
  27. ->range(0, 10);
  28. $result = $query->execute();
  29.  
  30. if (isset($result['node'])) {
  31. $nids = array_keys($result['node']);
  32. $nodes = entity_load('node', $nids);
  33.  
  34. foreach ($nodes as $node) {
  35. $node->field_summary_accomodation[LANGUAGE_NONE][0]['value'] = 1;
  36. node_save($node);
  37. // Store the last node id and update progress.
  38. $sandbox['last_nid'] = $node->nid;
  39. $sandbox['progress']++;
  40. }
  41. }
  42.  
  43. // Set the finished variable based on the current progress status.
  44. $sandbox['#finished'] = $sandbox['progress'] / $sandbox['total'];
  45.  
  46. return t('Summary accomodation field is enabled by default.');
  47. }