n How To Use Batch API in Drupal 8 & 9 | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

According to Drupal.org batch operations can be defined as "Functions allowing forms processing to be spread out over several page requests, thus ensuring that the processing does not get interrupted because of a PHP timeout, while allowing the user to receive feedback on the progress of the ongoing operations."

in this tuto, I will create a batch process to delete all Nodes. So let’s create a small module for that.

codimth_batch.info.yml

name: Codimth Batch
type: module
description: An example how to use batch api in drupal 8 & 9.
package: Codimth
core_version_requirement: ^8 || ^9

codimth_batch.routing.yml

codimth_batch.form:
  path: '/codimth_batch'
  defaults:
    _form: '\Drupal\codimth_batch\Form\CodimthBatchForm'
    _title: 'Demo of batch processing'
  requirements:
    _permission: 'access content'

src/Form/CodimthBatchForm.php

<?php

namespace Drupal\codimth_batch\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Form with examples on how to use batch api.
 */
class CodimthBatchForm extends FormBase {

    /**
     * {@inheritdoc}
     */
    public function getFormId() {
        return 'codimth_batch_form';
    }

    /**
     * {@inheritdoc}
     */
    public function buildForm(array $form, FormStateInterface $form_state) {

        $form['delete_node'] = array(
            '#type' => 'submit',
            '#value' => $this->t('Delete All Nodes'),
        );
        return $form;
    }

    /**
     * {@inheritdoc}
     */
    public function submitForm(array &$form, FormStateInterface $form_state) {
        $nids = \Drupal::entityQuery('node')->execute();
        $operations = [
            ['delete_nodes_example', [$nids]],
        ];
        $batch = [
            'title' => $this->t('Deleting All Nodes ...'),
            'operations' => $operations,
            'finished' => 'delete_nodes_finished',
        ];
        batch_set($batch);
    }

}

batch_set() : Adds a new batch.

$batch is an array of steps to be performed in batch process. 

title: A safe, translated string to use as the title for the progress page. Defaults to t('Processing').

finished: Name of an implementation of callback_batch_finished(). This is executed after the batch has completed.

operations: (required) Array of operations to be performed, where each item is an array consisting of the name of an implementation of callback_batch_operation() and an array of parameter.

delete_nodes_example() This is the function that is called on each operation.

delete_nodes_finished() Batch 'finished' callback.

codimth_batch.module

<?php
use Drupal\node\Entity\Node;


function delete_nodes_example($nids, &$context){
    $message = 'Deleting ALL Nodes ...';
    $results = array();
    foreach ($nids as $nid) {
        $node = Node::load($nid);
        $results[] = $node->delete();
    }
    $context['message'] = $message;
    $context['results'] = $results;
}

function delete_nodes_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 post processed.', '@count posts processed.'
        );
    }
    else {
        $message = t('Finished with an error.');
    }
    \Drupal::messenger()->addStatus($message);
}

Next steps

  • Clear your Drupal caches. To do this I use this Drush command: drush cr if you don’t currently use Drush, I highly recommend using it, or the Drupal Console.
  • Now, go back to your site, and you should be able to see the new page "/codimth_batch" you have just created.
  • I hope you found this article useful. let me know if you have any questions and I’ll be happy to answer them.

 

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook