Creating the batch

Inside the JsonImporter::import() method, once we get our hands on the $products array, let's replace the loop with the following:

$batch = [
  'title' => $this->t('Importing products'),
  'operations' => [
    [[$this, 'clearMissing'], [$products]],
    [[$this, 'importProducts'], [$products]],
  ],
  'finished' => [$this, 'importProductsFinished'],
];
batch_set($batch);

Creating a batch involves a number of steps, the first one being the creation of a batch definition, which is nothing more than an array with some data. The title option sets the title to be used on the progress page. Similarly, we also have the optional init_message, progress_message and error_message, which have some sensible defaults, so we won't set them here. For ...

Get Drupal 8 Module Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.