- Issue created by @zilloww
I'm creating a contrib Drupal module using the Batch API to create a .zip archive and populate it with some data. The issue is that I cannot find a clean way to start client-side download of the archive once the batch is finished.
I have two main files. The file Form/ExportForm.php that takes some parameters and on submit, calls a service to start the batch and my second main file is Service/BatchService.php. This service handles the whole batch process. Here are the simplified contents of these files:
ExportForm.php
class ExportForm extends FormBase {
// ...
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->batchService->batch_start($form_state->getValue('parameter'));
}
}
BatchService.php
class BatchService {
// ...
public function batch_start($parameter) {
$archiveName = "archive.zip";
$realpath = \Drupal::service('file_system')->realpath("private://export");
$zip = new \ZipArchive();
$zip->open($realpath . '/' . $archiveName);
// Get data to process
$data = $this->helperService->getData();
$operations = [];
foreach ($data as $element) {
$operations[] = [
'...\BatchService::batch_operation_process_element', [$element]
];
}
$batch = [
'title' => t('Processing...'),
'operations' => $operations,
'finished' => '...\BatchService::batch_operation_finished'
];
batch_set($batch);
}
public static function batch_operation_process_element($element, &$context) {
// Process element and add it to the zip archive.
}
public static function batch_operation_finished($success, $results, $operations) {
if ($success) {
unlink($results['archivePath']);
}
}
}
I searched for issues and solutions but didn't found anything. If someone finds a patch, a solution or another issue answering this question, let me know. Thank you all!
Active
10.2 ✨