Skip to main content

[Drupal] Batch API trong Drupal - example

Giới thiệu về Batch API trong Drupal

Batch API được định nghĩa là chức năng cho phép xử lý biểu mẫu bằng cách chia nhỏ theo từng request, đảm bảo rằng quá trình xử lý không bị gián đoạn do hết thời gian chờ PHP (timeout) đồng thời cho phép người dùng nhận phản hồi về tiến trình của các hoạt động đang diễn ra.

Đây là sơ đồ để hiểu cơ chế hoạt động của Batch API:

Image
Đây là sơ đồ để hiểu cơ chế hoạt động của Batch API:

Dưới đây là một ví dụ tạo một Batch API xoá tất cả các Nodes

Snippet Code Tạo Batch API trong Drupal

Tạo module custom, trong custom_module.info.yml

name: Custom Module
type: module
description: An example how to use batch api in drupal.
package: Custom
core_version_requirement: ^9 || ^10

custom_module.routing.yml

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

src/Form/CustomModuleBatchForm.php

<?php
namespace Drupal\custom_module\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Form with examples on how to use batch api.
*/
class CustomModuleBatchForm extends FormBase {
   /**
    * {@inheritdoc}
    */
   public function getFormId() {
       return 'custom_module_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 = [
           ['function_delete_nodes_example', [$nids]],
       ];
       $batch = [
           'title' => $this->t('Deleting All Nodes ...'),
           'operations' => $operations,
           'finished' => 'function_delete_nodes_finished',
       ];
       batch_set($batch);
   }
}

batch_set() : Tạo một batch.

$batch là một loạt các bước được thực hiện trong quy trình

title: Một chuỗi được dịch an toàn để sử dụng làm tiêu đề cho trang tiến trình. Mặc định là t('Đang xử lý')