function BatchExampleForm::generateBatch1

Same name and namespace in other branches
  1. 4.0.x modules/batch_example/src/Form/BatchExampleForm.php \Drupal\batch_example\Form\BatchExampleForm::generateBatch1()

Generate Batch 1.

Batch 1 will process one item at a time.

This creates an operations array defining what batch 1 should do, including what it should do when it's finished. In this case, each operation is the same and by chance even has the same $nid to operate on, but we could have a mix of different types of operations in the operations array.

1 call to BatchExampleForm::generateBatch1()
BatchExampleForm::submitForm in modules/batch_example/src/Form/BatchExampleForm.php
Form submission handler.

File

modules/batch_example/src/Form/BatchExampleForm.php, line 76

Class

BatchExampleForm
Form with examples on how to use cache.

Namespace

Drupal\batch_example\Form

Code

public function generateBatch1() {
    $num_operations = 1000;
    $this->messenger()
        ->addMessage($this->t('Creating an array of @num operations', [
        '@num' => $num_operations,
    ]));
    $operations = [];
    // Set up an operations array with 1000 elements, each doing function
    // batch_example_op_1.
    // Each operation in the operations array means at least one new HTTP
    // request, running Drupal from scratch to accomplish the operation. If the
    // operation returns with $context['finished'] != TRUE, then it will be
    // called again.
    // In this example, $context['finished'] is always TRUE.
    for ($i = 0; $i < $num_operations; $i++) {
        // Each operation is an array consisting of
        // - The function to call.
        // - An array of arguments to that function.
        $operations[] = [
            'batch_example_op_1',
            [
                $i + 1,
                $this->t('(Operation @operation)', [
                    '@operation' => $i,
                ]),
            ],
        ];
    }
    $batch = [
        'title' => $this->t('Creating an array of @num operations', [
            '@num' => $num_operations,
        ]),
        'operations' => $operations,
        'finished' => 'batch_example_finished',
    ];
    return $batch;
}