I'm trying to write a module to duplicate a series of nodes and to make sure there is no timeout I want to use the Batch Api for this.
This is what I have at this moment in src/Controller/NodeCloneController.php:
namespace Drupal\book_clone\Controller; use Drupal\Core\Controller\ControllerBase; use Drupal\node\Entity\Node; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Class CloneNodesController. */ class CloneNodesController extends ControllerBase { /** * Clone nodes. */ public function cloneNodes() { $nids = [55,92,86]; $this->book_clone_clone_multiple_nodes($nids); $this->messenger()->addMessage($this->t('Nodes are being cloned.')); return $this->redirect('system.admin_content'); } function book_clone_clone_multiple_nodes(array $nids) { $operations = []; foreach ($nids as $nid) { $operations[] = [ [ $this->book_clone_clone_node($nid), [], ], ]; } $batch = [ 'title' => t('Cloning'), 'operations' => $operations, 'finished' => $this->book_clone_batch_finished(), ]; batch_set($batch); } function book_clone_clone_node($nid) { $node = Node::load($nid); if ($node) { $cloned_node = $node->createDuplicate(); $cloned_node->save(); } } function book_clone_batch_finished() { $message = t('Finished'); \Drupal::messenger()->addMessage($message); } } The function cloneNodes is called by going to a specific admin path via a routing file:
book_clone.clone_nodes: path: '/admin/content/clone' defaults: _controller: '\Drupal\book_clone\Controller\CloneNodesController::cloneNodes' _title: 'Clone Nodes' requirements: _permission: 'access content' Cloning works with this code but I don't see the batch page and progressbar. So I don't know if the batch is working and I want to show this page for my users to get proper feedback. First time using Batch so I think i'm missing something here. What am I doing wrong?