Skip to main content

What is Batch?

     Batch process is a program of execution in a sequence without disturbance of external source manually.Drupal development allows large amounts of data to be processed without setting inappropriate pressure on the server.It is an important aspects of drupal development.It can easily run a process without an end user’s involvement.

Batch process:

      To perform the drupal batch process we need a form from which we can trigger the batch process. Here we will create a batch to bulk delete all Nodes at a time.

      To setup a batch operation you need to construct an array that contains a number of elements. This array is then passed into the batch_set() function, which generates the needed setup for the batch inside Drupal.

Module for batch process:
my_batch.info.yml

name: my_batch
type: module
description: My Batch Example
core: 8.x
package: Example

Name - Name of the module (Eg:my_batch)
Type - It indicates the type of extension. Use module, theme or profile.
Description - Displayed on the module administration page.
Core - Specifies the version of Drupal core that your module is compatible with.
Package - It allows you to group like modules together.

 

my_batch.routing.yml

my_batch.bulk_delete:
  path: '/my-batch/delete'
  defaults:
    _form: '\Drupal\my_batch\Form\BulkDeleteForm'
    _title: 'My Batch'
  requirements:
    _permission: 'access content'

path(required) - The URL to the route, with a leading forward slash (e.g., path: '/my_batch).
defaults (required) - Defines the default properties of a route.
      _form - This one expects a classname implementing Drupal\Core\Form\FormInterface
      _title (optional) - The page title for the route. May differ from the menu link title.
requirements (required) - Determines what conditions must be met in order to grant access to the route.
     _permission - A permission string (e.g., _permission: 'access content'). You can specify multiple permissions by separating them with ',' (comma)

 

my_batch/src/Form/BulkDeleteForm.php

<?php
 namespace Drupal\my_batch\Form;
 use Drupal\Core\Form\FormBase;
 use Drupal\Core\Form\FormStateInterface;
/**
 * Class BulkDeleteForm.
 *
 * @package Drupal\my_batch\Form
 */
class BulkDeleteForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'bulk_delete_form';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['bulk_delete'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Bulk Delete'),
    );
    return $form;
  }
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $nids = \Drupal::entityQuery('node')
      ->condition('type', 'batch')
      ->sort('created', 'ASC')
      ->execute();
    $batch = array(
      'title' => t('Bulk Delete...'),
      'operations' => array(
        array(
          '\Drupal\my_batch\BulkDeleteNode::bulkDelete',
          array($nids)
        ),
      ),
      'finished' => '\Drupal\my_batch\BulkDeleteNode::bulkDeleteFinishedCallback',
    );
    batch_set($batch);
  }
}

batch_set - It will execute set of operations which is made in batches without interrupt other process.
$batch - It  is an array of steps to be performed in batch process.

 

my_batch/src/BulkDeleteNode.php

<?php
namespace Drupal\my_batch;
use Drupal\node\Entity\Node;
class BulkDeleteNode {
  public static function bulkDelete($nids, &$context){
    $message = 'Bulk delete...';
    $results = array();
    foreach ($nids as $nid) {
      $node = Node::load($nid);
      $results[] = $node->delete();
    }
    $context['message'] = $message;
    $context['results'] = $results;
  }
  
function bulkDeleteFinishedCallback($success, $results, $operations) {
    if ($success) {
      $message = \Drupal::translation()->formatPlural(
        count($results),
        'One node deleted.', '@count nodes deleted.'
      );
    }
    else {
      $message = t('Encountered an error on delete.');
    }
    drupal_set_message($message);
  }
}

bulkDelete - This function is used to handle the process of deleting node.
bulkDeleteFinishedCallback - This is the finish call back function it will be called once deletion of all node is done. It will give the status message of the process.

 

Advantages of using batch:

  • It can easily run through the large amount of items without using up all of the server resources in a single page load.
  • Suppose we are migrating from drupal 7 to drupal 8, we need to import a bunch of nodes from drupal 7. For that situation we can use batch process.
  • Deleting a bulk of nodes without disturbing the other process.
  • It is used to perform an action on a number of users.
Contributor(s)
Drupal Tags

Comments