Drupal 8 batch operations example

Batch is handy here is one way you can use it:

<?php
/**
 * Helper function to install a module.
 *
 * @param string $module
 *   This is the module name.
 *
 * @return bool
 *   This returns true.
 */
function mymodule_install_module(string $module) {
  \Drupal::service('module_installer')->install([$module]);
  return TRUE;
}

/**
 * A batch function to install online lodgments.
 */
function mymodule_batch_install_batch() {
  $modules = [
    'some_module',
    'some_other_module'
// add way more here 
  ];
  $operations = [];
  foreach ($modules as $module) {
    $operations[] = ['mymodule_install_module', [$module]];
  }
  $batch = [
    'operations' => $operations,
    'finished' => 'mymodule_batch_install_finished',
    'title' => t('Processing Modules'),
    'init_message' => t('Processing Modules'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('Batch 2 has encountered an error.'),
  ];
  batch_set($batch);
}

/**
 * Function for batch finish.
 *
 * @param mixed $success
 *   Batch sucess.
 * @param mixed $results
 *   Batch results.
 * @param mixed $operations
 *   Batch operations.
 */
function mymodule_batch_install_finished($success, $results, $operations) {
  drupal_flush_all_caches();
  drupal_set_message(t('OLL has been installed'), 'status');
}

 

Category: