Batch Boilerplate

Public

Provides a general boilerplate for chunked batch processes. @see http://drupal.org/node/180528 for a more detailed explanation of batches.

</> CopyGet raw version
php
  1. <?php
  2.  
  3. function my_batch_name(){
  4. $chunk_size = 120; // Items per run to process
  5.  
  6. // Get the data array
  7. $data = get_data();
  8.  
  9. // Batch init
  10. $batch = array(
  11. 'title' => t('My title ...'), // Change to the batch title
  12. 'operations' => array(),
  13. 'init_message' => t('Commencing'),
  14. 'progress_message' => t('Processed @current out of @total.'),
  15. //'file' => drupal_get_path('module', 'mymodule') . '/includes/my_batch_name.inc',
  16. 'error_message' => t('An error occurred during processing'),
  17. 'finished' => 'batch_finished',
  18. 'progressive' => FALSE
  19. );
  20.  
  21. if ($data){
  22. $chunks = array_chunk($data, $chunk_size);
  23. $count_chunks = count($chunks);
  24.  
  25. $i = 1 ;
  26. foreach($chunks as $chunk){
  27. $batch['operations'][] = array('process_chunk', array($chunk, 'details' => t('(Importing chunk @chunk of @count)', array('@chunk '=> $i, '@count'=> $count_chunks))));
  28. //if ($i == 1) break; // Debugging purposes - Break on the first run.
  29. $i++;
  30. }
  31. }
  32. batch_set($batch);
  33. batch_process('<front>'); //Change to the desired batch finish page.
  34. }
  35.  
  36. function get_data(){
  37. $query = new EntityFieldQuery();
  38. // do the query / get the data
  39.  
  40. $results = $query->execute();
  41. if (isset($results['node'])){
  42. return array_keys($results['node']);
  43. }
  44. return array();
  45. }
  46.  
  47. // Batch operation: Process chunks.
  48. function process_chunk($data_chunk, $operation_details, &$context){
  49. foreach($data_chunk as $data){
  50. // Do the processing
  51. // $node = node_load($data);
  52. // node_save($node);
  53. }
  54. $context['message'] = $operation_details; //Will show what chunk we're on.
  55. }
  56.  
  57. function batch_finished($success, $results, $operations){
  58. if ($success) {
  59. $message = 'Success.'; // Customize success message.
  60. }
  61. else {
  62. $message = 'There were errors in the operations. Could not complete the process';
  63. }
  64. drupal_set_message($message);
  65. }

Comments