2

I followed Smack My Batch Up : Batch Processing In Drupal 8 article to create a batch job and all works fine. But in the finish callback I can't get the total number of processed elements.

This is my code:

$operations = [];
foreach ($lines as $line) {
/*
Here I have an array of operations and each element have the name of 
the operation callback function and the line that should be processed.
Maybe this is the problem.
*/
  $operations[] = ['process_line_saint_du_jour', [$line]];
}

$batch = array(
  'title' => t('Migrating Saint of the Day'),
  'operations' => $operations,
  'finished' => 'process_line_saint_du_jour_batch_finished',
  'init_message' => t('Saint of the Day migration is starting.'),
  'progress_message' => t('Processed @current out of @total. Estimated time: @estimate.'),
  'error_message' => t('The migration process has encountered an error.'),
  'file' => drupal_get_path('module', 'diocese_migrate') . '/diocese_migrate.batch.inc',
);

batch_set($batch);

This is my finish callback function:

function process_line_saint_du_jour_batch_finished($success, $results, $operations) {
  // The 'success' parameter means no fatal PHP errors were detected. All
  // other error management should be handled using 'results'.
  if ($success) {
    $message = \Drupal::translation()->formatPlural(
      count($results),
      'One Saint of the Day processed.', '@count Saint of the Day processed.'
    );
  }
  else {
    $message = t('Finished with an error.');
  }
  drupal_set_message($message);
}

The problem here is that I have only one element in the $results array and I have processed 366 elements, all works fine but at the end of the batch I have the following message:

One Saint of the Day processed.

3

Reading the Batch Process in Drupal 8 and Drupal 8 Batch Example articles I found the answer.

The key is in the

//Message to show during each execution of the callback function
$context['message']
//Array with the total of processed items.
$context['results']

So, the solution is in the operations callback function, now the functions is like this and it works:

function process_line_saint_du_jour($line, &$context) {
  //Custom Code
  $info = str_getcsv($line, ";", '"');
  $context['results'][] = $info[3];
  $context['message'] = t('Migrating Saint du jour @day', array('@day' => $info[3]));
}
3
  • where does $info comes from, I guess it should be $line[3]? Dec 24 '19 at 13:02
  • @KrishnaMohan I added the missing line, but I just take a piece of code to show how it works. Dec 24 '19 at 17:36
  • Yeah I know. just to make it clean :) Dec 30 '19 at 9:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.