Drupal 8 Batch Example
Category:
I'm in the middle of migrating a Drupal 6 site to Drupal 8 and need to write a batch in Drupal 8 to pull in a bunch of nodes from Drupal 6, so I thought I would document the process to help others.
Related api docs: https://api.drupal.org/api/drupal/core%21includes%21form.inc/group/batch/8
My module's name is disc, so be sure to replace any occurences of it with your module's name.
disc/disc.routing.yml
disc.batch: path: '/disc-batch' defaults: _controller: '\Drupal\disc\Controller\DiscBatchController::content' _title: 'Disc Batch' requirements: _permission: 'administer content'
disc/src/Controller/DiscBatchController.php
<?php /** * @file * Contains \Drupal\disc\Controller\DiscBatchController. */ namespace Drupal\disc\Controller; class DiscBatchController { public function content() { $batch = array( 'title' => t('Exporting'), 'operations' => array( array('disc_migrate', array('courses', array('foo' => 'bar'))), ), 'finished' => 'disc_migrate_finished_callback', 'file' => drupal_get_path('module', 'disc') . '/disc.migrate.inc', ); batch_set($batch); return batch_process('user'); } }
disc/disc.migrate.inc
<?php function disc_migrate($type, $options = array(), &$context) { // Do heavy coding here... $message = 'Ready spaghetti...'; switch ($type) { case 'courses': $message = 'migrating courses...'; $context['results'][] = $options; break; default: $message = 'migrating somethine else...'; break; } $context['message'] = $message; } function disc_migrate_finished_callback($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 post processed.', '@count posts processed.' ); } else { $message = t('Finished with an error.'); } drupal_set_message($message); //$_SESSION['disc_migrate_batch_results'] = $results; }
Testing
Now when I navigate to http://example.com/disc-batch my batch script runs. That's all folks. Maybe I can run faster?