diff --git a/src/Controller/CRUDController.php b/src/Controller/CRUDController.php index 7809b32b2b..39496e8107 100644 --- a/src/Controller/CRUDController.php +++ b/src/Controller/CRUDController.php @@ -525,15 +525,17 @@ public function batchAction(Request $request): Response } } - if (\count($idx) > 0) { - $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx); - } elseif (!$allElements) { - $this->addFlash( - 'sonata_flash_info', - $this->trans('flash_batch_no_elements_processed', [], 'SonataAdminBundle') - ); + if (!$allElements) { + if (\count($idx) > 0) { + $this->admin->getModelManager()->addIdentifiersToQuery($this->admin->getClass(), $query, $idx); + } else { + $this->addFlash( + 'sonata_flash_info', + $this->trans('flash_batch_no_elements_processed', [], 'SonataAdminBundle') + ); - return $this->redirectToList(); + return $this->redirectToList(); + } } return \call_user_func($batchActionExecutable, $query, $forwardedRequest); diff --git a/tests/Controller/CRUDControllerTest.php b/tests/Controller/CRUDControllerTest.php index 7b4b55fcea..96e33e2603 100644 --- a/tests/Controller/CRUDControllerTest.php +++ b/tests/Controller/CRUDControllerTest.php @@ -4512,6 +4512,53 @@ public function testBatchActionWithRequesData(): void static::assertSame('bar', $this->request->request->get('foo')); } + public function testBatchActionWithRequesDataIdsAndAllItems(): void + { + $batchActions = ['delete' => ['label' => 'Foo Bar', 'ask_confirmation' => false]]; + + $this->admin->expects(static::exactly(2)) + ->method('getBatchActions') + ->willReturn($batchActions); + + $this->expectGetController(); + + $datagrid = $this->createMock(DatagridInterface::class); + + $query = $this->createMock(ProxyQueryInterface::class); + $datagrid->expects(static::once()) + ->method('getQuery') + ->willReturn($query); + + $this->admin->expects(static::once()) + ->method('getDatagrid') + ->willReturn($datagrid); + + $this->httpKernel->expects(static::once()) + ->method('handle') + ->willReturn($response = new Response()); + + $modelManager = $this->createMock(ModelManagerInterface::class); + + $this->admin + ->method('getModelManager') + ->willReturn($modelManager); + + $this->admin + ->method('getClass') + ->willReturn('Foo'); + + $modelManager->expects(static::never()) + ->method('addIdentifiersToQuery'); + + $this->request->setMethod(Request::METHOD_POST); + $this->request->request->set('data', json_encode(['action' => 'delete', 'idx' => ['123', '456'], 'all_elements' => true])); + $this->request->request->set('_sonata_csrf_token', 'csrf-token-123_sonata.batch'); + + $result = $this->controller->batchAction($this->request); + + static::assertSame($response, $result); + } + /** * @phpstan-return iterable */