vendor/easycorp/easyadmin-bundle/src/Controller/AbstractCrudController.php line 116

Open in your IDE?
  1. <?php
  2. namespace EasyCorp\Bundle\EasyAdminBundle\Controller;
  3. use Doctrine\DBAL\Exception\ForeignKeyConstraintViolationException;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use Doctrine\ORM\QueryBuilder;
  6. use Doctrine\Persistence\ManagerRegistry;
  7. use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
  8. use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
  9. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  10. use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
  11. use EasyCorp\Bundle\EasyAdminBundle\Config\Assets;
  12. use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
  13. use EasyCorp\Bundle\EasyAdminBundle\Config\Filters;
  14. use EasyCorp\Bundle\EasyAdminBundle\Config\KeyValueStore;
  15. use EasyCorp\Bundle\EasyAdminBundle\Config\Option\EA;
  16. use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
  17. use EasyCorp\Bundle\EasyAdminBundle\Contracts\Controller\CrudControllerInterface;
  18. use EasyCorp\Bundle\EasyAdminBundle\Dto\AssetsDto;
  19. use EasyCorp\Bundle\EasyAdminBundle\Dto\BatchActionDto;
  20. use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
  21. use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
  22. use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
  23. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
  24. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityDeletedEvent;
  25. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
  26. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
  27. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  28. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityDeletedEvent;
  29. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityPersistedEvent;
  30. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  31. use EasyCorp\Bundle\EasyAdminBundle\Exception\EntityRemoveException;
  32. use EasyCorp\Bundle\EasyAdminBundle\Exception\ForbiddenActionException;
  33. use EasyCorp\Bundle\EasyAdminBundle\Exception\InsufficientEntityPermissionException;
  34. use EasyCorp\Bundle\EasyAdminBundle\Factory\ActionFactory;
  35. use EasyCorp\Bundle\EasyAdminBundle\Factory\ControllerFactory;
  36. use EasyCorp\Bundle\EasyAdminBundle\Factory\EntityFactory;
  37. use EasyCorp\Bundle\EasyAdminBundle\Factory\FilterFactory;
  38. use EasyCorp\Bundle\EasyAdminBundle\Factory\FormFactory;
  39. use EasyCorp\Bundle\EasyAdminBundle\Factory\PaginatorFactory;
  40. use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
  41. use EasyCorp\Bundle\EasyAdminBundle\Field\BooleanField;
  42. use EasyCorp\Bundle\EasyAdminBundle\Form\Type\FileUploadType;
  43. use EasyCorp\Bundle\EasyAdminBundle\Form\Type\FiltersFormType;
  44. use EasyCorp\Bundle\EasyAdminBundle\Form\Type\Model\FileUploadState;
  45. use EasyCorp\Bundle\EasyAdminBundle\Orm\EntityRepository;
  46. use EasyCorp\Bundle\EasyAdminBundle\Orm\EntityUpdater;
  47. use EasyCorp\Bundle\EasyAdminBundle\Provider\AdminContextProvider;
  48. use EasyCorp\Bundle\EasyAdminBundle\Provider\FieldProvider;
  49. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  50. use EasyCorp\Bundle\EasyAdminBundle\Security\Permission;
  51. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  52. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  53. use Symfony\Component\Form\FormBuilderInterface;
  54. use Symfony\Component\Form\FormInterface;
  55. use Symfony\Component\HttpFoundation\JsonResponse;
  56. use Symfony\Component\HttpFoundation\RedirectResponse;
  57. use Symfony\Component\HttpFoundation\Response;
  58. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  59. use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
  60. use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
  61. use function Symfony\Component\String\u;
  62. /**
  63.  * @author Javier Eguiluz <javier.eguiluz@gmail.com>
  64.  */
  65. abstract class AbstractCrudController extends AbstractController implements CrudControllerInterface
  66. {
  67.     abstract public static function getEntityFqcn(): string;
  68.     public function configureCrud(Crud $crud): Crud
  69.     {
  70.         return $crud;
  71.     }
  72.     public function configureAssets(Assets $assets): Assets
  73.     {
  74.         return $assets;
  75.     }
  76.     public function configureActions(Actions $actions): Actions
  77.     {
  78.         return $actions;
  79.     }
  80.     public function configureFilters(Filters $filters): Filters
  81.     {
  82.         return $filters;
  83.     }
  84.     public function configureFields(string $pageName): iterable
  85.     {
  86.         return $this->container->get(FieldProvider::class)->getDefaultFields($pageName);
  87.     }
  88.     public static function getSubscribedServices(): array
  89.     {
  90.         return array_merge(parent::getSubscribedServices(), [
  91.             'doctrine' => '?'.ManagerRegistry::class,
  92.             'event_dispatcher' => '?'.EventDispatcherInterface::class,
  93.             ActionFactory::class => '?'.ActionFactory::class,
  94.             AdminContextProvider::class => '?'.AdminContextProvider::class,
  95.             AdminUrlGenerator::class => '?'.AdminUrlGenerator::class,
  96.             ControllerFactory::class => '?'.ControllerFactory::class,
  97.             EntityFactory::class => '?'.EntityFactory::class,
  98.             EntityRepository::class => '?'.EntityRepository::class,
  99.             EntityUpdater::class => '?'.EntityUpdater::class,
  100.             FieldProvider::class => '?'.FieldProvider::class,
  101.             FilterFactory::class => '?'.FilterFactory::class,
  102.             FormFactory::class => '?'.FormFactory::class,
  103.             PaginatorFactory::class => '?'.PaginatorFactory::class,
  104.         ]);
  105.     }
  106.     public function index(AdminContext $context)
  107.     {
  108.         $event = new BeforeCrudActionEvent($context);
  109.         $this->container->get('event_dispatcher')->dispatch($event);
  110.         if ($event->isPropagationStopped()) {
  111.             return $event->getResponse();
  112.         }
  113.         if (!$this->isGranted(Permission::EA_EXECUTE_ACTION, ['action' => Action::INDEX'entity' => null])) {
  114.             throw new ForbiddenActionException($context);
  115.         }
  116.         $fields FieldCollection::new($this->configureFields(Crud::PAGE_INDEX));
  117.         $context->getCrud()->setFieldAssets($this->getFieldAssets($fields));
  118.         $filters $this->container->get(FilterFactory::class)->create($context->getCrud()->getFiltersConfig(), $fields$context->getEntity());
  119.         $queryBuilder $this->createIndexQueryBuilder($context->getSearch(), $context->getEntity(), $fields$filters);
  120.         $paginator $this->container->get(PaginatorFactory::class)->create($queryBuilder);
  121.         // this can happen after deleting some items and trying to return
  122.         // to a 'index' page that no longer exists. Redirect to the last page instead
  123.         if ($paginator->isOutOfRange()) {
  124.             return $this->redirect($this->container->get(AdminUrlGenerator::class)
  125.                 ->set(EA::PAGE$paginator->getLastPage())
  126.                 ->generateUrl());
  127.         }
  128.         $entities $this->container->get(EntityFactory::class)->createCollection($context->getEntity(), $paginator->getResults());
  129.         $this->container->get(EntityFactory::class)->processFieldsForAll($entities$fields);
  130.         $actions $this->container->get(EntityFactory::class)->processActionsForAll($entities$context->getCrud()->getActionsConfig());
  131.         $responseParameters $this->configureResponseParameters(KeyValueStore::new([
  132.             'pageName' => Crud::PAGE_INDEX,
  133.             'templateName' => 'crud/index',
  134.             'entities' => $entities,
  135.             'paginator' => $paginator,
  136.             'global_actions' => $actions->getGlobalActions(),
  137.             'batch_actions' => $actions->getBatchActions(),
  138.             'filters' => $filters,
  139.         ]));
  140.         $event = new AfterCrudActionEvent($context$responseParameters);
  141.         $this->container->get('event_dispatcher')->dispatch($event);
  142.         if ($event->isPropagationStopped()) {
  143.             return $event->getResponse();
  144.         }
  145.         return $responseParameters;
  146.     }
  147.     public function detail(AdminContext $context)
  148.     {
  149.         $event = new BeforeCrudActionEvent($context);
  150.         $this->container->get('event_dispatcher')->dispatch($event);
  151.         if ($event->isPropagationStopped()) {
  152.             return $event->getResponse();
  153.         }
  154.         if (!$this->isGranted(Permission::EA_EXECUTE_ACTION, ['action' => Action::DETAIL'entity' => $context->getEntity()])) {
  155.             throw new ForbiddenActionException($context);
  156.         }
  157.         if (!$context->getEntity()->isAccessible()) {
  158.             throw new InsufficientEntityPermissionException($context);
  159.         }
  160.         $this->container->get(EntityFactory::class)->processFields($context->getEntity(), FieldCollection::new($this->configureFields(Crud::PAGE_DETAIL)));
  161.         $context->getCrud()->setFieldAssets($this->getFieldAssets($context->getEntity()->getFields()));
  162.         $this->container->get(EntityFactory::class)->processActions($context->getEntity(), $context->getCrud()->getActionsConfig());
  163.         $responseParameters $this->configureResponseParameters(KeyValueStore::new([
  164.             'pageName' => Crud::PAGE_DETAIL,
  165.             'templateName' => 'crud/detail',
  166.             'entity' => $context->getEntity(),
  167.         ]));
  168.         $event = new AfterCrudActionEvent($context$responseParameters);
  169.         $this->container->get('event_dispatcher')->dispatch($event);
  170.         if ($event->isPropagationStopped()) {
  171.             return $event->getResponse();
  172.         }
  173.         return $responseParameters;
  174.     }
  175.     public function edit(AdminContext $context)
  176.     {
  177.         $event = new BeforeCrudActionEvent($context);
  178.         $this->container->get('event_dispatcher')->dispatch($event);
  179.         if ($event->isPropagationStopped()) {
  180.             return $event->getResponse();
  181.         }
  182.         if (!$this->isGranted(Permission::EA_EXECUTE_ACTION, ['action' => Action::EDIT'entity' => $context->getEntity()])) {
  183.             throw new ForbiddenActionException($context);
  184.         }
  185.         if (!$context->getEntity()->isAccessible()) {
  186.             throw new InsufficientEntityPermissionException($context);
  187.         }
  188.         $this->container->get(EntityFactory::class)->processFields($context->getEntity(), FieldCollection::new($this->configureFields(Crud::PAGE_EDIT)));
  189.         $context->getCrud()->setFieldAssets($this->getFieldAssets($context->getEntity()->getFields()));
  190.         $this->container->get(EntityFactory::class)->processActions($context->getEntity(), $context->getCrud()->getActionsConfig());
  191.         $entityInstance $context->getEntity()->getInstance();
  192.         if ($context->getRequest()->isXmlHttpRequest()) {
  193.             if ('PATCH' !== $context->getRequest()->getMethod()) {
  194.                 throw new MethodNotAllowedHttpException(['PATCH']);
  195.             }
  196.             if (!$this->isCsrfTokenValid(BooleanField::CSRF_TOKEN_NAME$context->getRequest()->query->get('csrfToken'))) {
  197.                 if (class_exists(InvalidCsrfTokenException::class)) {
  198.                     throw new InvalidCsrfTokenException();
  199.                 } else {
  200.                     return new Response('Invalid CSRF token.'400);
  201.                 }
  202.             }
  203.             $fieldName $context->getRequest()->query->get('fieldName');
  204.             $newValue 'true' === mb_strtolower($context->getRequest()->query->get('newValue'));
  205.             try {
  206.                 $event $this->ajaxEdit($context->getEntity(), $fieldName$newValue);
  207.             } catch (\Exception) {
  208.                 throw new BadRequestHttpException();
  209.             }
  210.             if ($event->isPropagationStopped()) {
  211.                 return $event->getResponse();
  212.             }
  213.             return new Response($newValue '1' '0');
  214.         }
  215.         $editForm $this->createEditForm($context->getEntity(), $context->getCrud()->getEditFormOptions(), $context);
  216.         $editForm->handleRequest($context->getRequest());
  217.         if ($editForm->isSubmitted() && $editForm->isValid()) {
  218.             $this->processUploadedFiles($editForm);
  219.             $event = new BeforeEntityUpdatedEvent($entityInstance);
  220.             $this->container->get('event_dispatcher')->dispatch($event);
  221.             $entityInstance $event->getEntityInstance();
  222.             $this->updateEntity($this->container->get('doctrine')->getManagerForClass($context->getEntity()->getFqcn()), $entityInstance);
  223.             $this->container->get('event_dispatcher')->dispatch(new AfterEntityUpdatedEvent($entityInstance));
  224.             return $this->getRedirectResponseAfterSave($contextAction::EDIT);
  225.         }
  226.         $responseParameters $this->configureResponseParameters(KeyValueStore::new([
  227.             'pageName' => Crud::PAGE_EDIT,
  228.             'templateName' => 'crud/edit',
  229.             'edit_form' => $editForm,
  230.             'entity' => $context->getEntity(),
  231.         ]));
  232.         $event = new AfterCrudActionEvent($context$responseParameters);
  233.         $this->container->get('event_dispatcher')->dispatch($event);
  234.         if ($event->isPropagationStopped()) {
  235.             return $event->getResponse();
  236.         }
  237.         return $responseParameters;
  238.     }
  239.     public function new(AdminContext $context)
  240.     {
  241.         $event = new BeforeCrudActionEvent($context);
  242.         $this->container->get('event_dispatcher')->dispatch($event);
  243.         if ($event->isPropagationStopped()) {
  244.             return $event->getResponse();
  245.         }
  246.         if (!$this->isGranted(Permission::EA_EXECUTE_ACTION, ['action' => Action::NEW, 'entity' => null])) {
  247.             throw new ForbiddenActionException($context);
  248.         }
  249.         if (!$context->getEntity()->isAccessible()) {
  250.             throw new InsufficientEntityPermissionException($context);
  251.         }
  252.         $context->getEntity()->setInstance($this->createEntity($context->getEntity()->getFqcn()));
  253.         $this->container->get(EntityFactory::class)->processFields($context->getEntity(), FieldCollection::new($this->configureFields(Crud::PAGE_NEW)));
  254.         $context->getCrud()->setFieldAssets($this->getFieldAssets($context->getEntity()->getFields()));
  255.         $this->container->get(EntityFactory::class)->processActions($context->getEntity(), $context->getCrud()->getActionsConfig());
  256.         $newForm $this->createNewForm($context->getEntity(), $context->getCrud()->getNewFormOptions(), $context);
  257.         $newForm->handleRequest($context->getRequest());
  258.         $entityInstance $newForm->getData();
  259.         $context->getEntity()->setInstance($entityInstance);
  260.         if ($newForm->isSubmitted() && $newForm->isValid()) {
  261.             $this->processUploadedFiles($newForm);
  262.             $event = new BeforeEntityPersistedEvent($entityInstance);
  263.             $this->container->get('event_dispatcher')->dispatch($event);
  264.             $entityInstance $event->getEntityInstance();
  265.             $this->persistEntity($this->container->get('doctrine')->getManagerForClass($context->getEntity()->getFqcn()), $entityInstance);
  266.             $this->container->get('event_dispatcher')->dispatch(new AfterEntityPersistedEvent($entityInstance));
  267.             $context->getEntity()->setInstance($entityInstance);
  268.             return $this->getRedirectResponseAfterSave($contextAction::NEW);
  269.         }
  270.         $responseParameters $this->configureResponseParameters(KeyValueStore::new([
  271.             'pageName' => Crud::PAGE_NEW,
  272.             'templateName' => 'crud/new',
  273.             'entity' => $context->getEntity(),
  274.             'new_form' => $newForm,
  275.         ]));
  276.         $event = new AfterCrudActionEvent($context$responseParameters);
  277.         $this->container->get('event_dispatcher')->dispatch($event);
  278.         if ($event->isPropagationStopped()) {
  279.             return $event->getResponse();
  280.         }
  281.         return $responseParameters;
  282.     }
  283.     public function delete(AdminContext $context)
  284.     {
  285.         $event = new BeforeCrudActionEvent($context);
  286.         $this->container->get('event_dispatcher')->dispatch($event);
  287.         if ($event->isPropagationStopped()) {
  288.             return $event->getResponse();
  289.         }
  290.         if (!$this->isGranted(Permission::EA_EXECUTE_ACTION, ['action' => Action::DELETE'entity' => $context->getEntity()])) {
  291.             throw new ForbiddenActionException($context);
  292.         }
  293.         if (!$context->getEntity()->isAccessible()) {
  294.             throw new InsufficientEntityPermissionException($context);
  295.         }
  296.         $csrfToken $context->getRequest()->request->get('token');
  297.         if ($this->container->has('security.csrf.token_manager') && !$this->isCsrfTokenValid('ea-delete'$csrfToken)) {
  298.             return $this->redirectToRoute($context->getDashboardRouteName());
  299.         }
  300.         $entityInstance $context->getEntity()->getInstance();
  301.         $event = new BeforeEntityDeletedEvent($entityInstance);
  302.         $this->container->get('event_dispatcher')->dispatch($event);
  303.         if ($event->isPropagationStopped()) {
  304.             return $event->getResponse();
  305.         }
  306.         $entityInstance $event->getEntityInstance();
  307.         try {
  308.             $this->deleteEntity($this->container->get('doctrine')->getManagerForClass($context->getEntity()->getFqcn()), $entityInstance);
  309.         } catch (ForeignKeyConstraintViolationException $e) {
  310.             throw new EntityRemoveException(['entity_name' => $context->getEntity()->getName(), 'message' => $e->getMessage()]);
  311.         }
  312.         $this->container->get('event_dispatcher')->dispatch(new AfterEntityDeletedEvent($entityInstance));
  313.         $responseParameters $this->configureResponseParameters(KeyValueStore::new([
  314.             'entity' => $context->getEntity(),
  315.         ]));
  316.         $event = new AfterCrudActionEvent($context$responseParameters);
  317.         $this->container->get('event_dispatcher')->dispatch($event);
  318.         if ($event->isPropagationStopped()) {
  319.             return $event->getResponse();
  320.         }
  321.         if (null !== $referrer $context->getReferrer()) {
  322.             return $this->redirect($referrer);
  323.         }
  324.         return $this->redirect($this->container->get(AdminUrlGenerator::class)->setAction(Action::INDEX)->unset(EA::ENTITY_ID)->generateUrl());
  325.     }
  326.     public function batchDelete(AdminContext $contextBatchActionDto $batchActionDto): Response
  327.     {
  328.         $event = new BeforeCrudActionEvent($context);
  329.         $this->container->get('event_dispatcher')->dispatch($event);
  330.         if ($event->isPropagationStopped()) {
  331.             return $event->getResponse();
  332.         }
  333.         if (!$this->isCsrfTokenValid('ea-batch-action-'.Action::BATCH_DELETE$batchActionDto->getCsrfToken())) {
  334.             return $this->redirectToRoute($context->getDashboardRouteName());
  335.         }
  336.         $entityManager $this->container->get('doctrine')->getManagerForClass($batchActionDto->getEntityFqcn());
  337.         $repository $entityManager->getRepository($batchActionDto->getEntityFqcn());
  338.         foreach ($batchActionDto->getEntityIds() as $entityId) {
  339.             $entityInstance $repository->find($entityId);
  340.             if (!$entityInstance) {
  341.                 continue;
  342.             }
  343.             $entityDto $context->getEntity()->newWithInstance($entityInstance);
  344.             if (!$this->isGranted(Permission::EA_EXECUTE_ACTION, ['action' => Action::DELETE'entity' => $entityDto])) {
  345.                 throw new ForbiddenActionException($context);
  346.             }
  347.             if (!$entityDto->isAccessible()) {
  348.                 throw new InsufficientEntityPermissionException($context);
  349.             }
  350.             $event = new BeforeEntityDeletedEvent($entityInstance);
  351.             $this->container->get('event_dispatcher')->dispatch($event);
  352.             $entityInstance $event->getEntityInstance();
  353.             try {
  354.                 $this->deleteEntity($entityManager$entityInstance);
  355.             } catch (ForeignKeyConstraintViolationException $e) {
  356.                 throw new EntityRemoveException(['entity_name' => $entityDto->toString(), 'message' => $e->getMessage()]);
  357.             }
  358.             $this->container->get('event_dispatcher')->dispatch(new AfterEntityDeletedEvent($entityInstance));
  359.         }
  360.         $responseParameters $this->configureResponseParameters(KeyValueStore::new([
  361.             'entity' => $context->getEntity(),
  362.             'batchActionDto' => $batchActionDto,
  363.         ]));
  364.         $event = new AfterCrudActionEvent($context$responseParameters);
  365.         $this->container->get('event_dispatcher')->dispatch($event);
  366.         if ($event->isPropagationStopped()) {
  367.             return $event->getResponse();
  368.         }
  369.         return $this->redirect($batchActionDto->getReferrerUrl());
  370.     }
  371.     public function autocomplete(AdminContext $context): JsonResponse
  372.     {
  373.         $queryBuilder $this->createIndexQueryBuilder($context->getSearch(), $context->getEntity(), FieldCollection::new([]), FilterCollection::new());
  374.         $autocompleteContext $context->getRequest()->get(AssociationField::PARAM_AUTOCOMPLETE_CONTEXT);
  375.         /** @var CrudControllerInterface $controller */
  376.         $controller $this->container->get(ControllerFactory::class)->getCrudControllerInstance($autocompleteContext[EA::CRUD_CONTROLLER_FQCN], Action::INDEX$context->getRequest());
  377.         /** @var FieldDto $field */
  378.         $field FieldCollection::new($controller->configureFields($autocompleteContext['originatingPage']))->getByProperty($autocompleteContext['propertyName']);
  379.         /** @var \Closure|null $queryBuilderCallable */
  380.         $queryBuilderCallable $field->getCustomOption(AssociationField::OPTION_QUERY_BUILDER_CALLABLE);
  381.         if (null !== $queryBuilderCallable) {
  382.             $queryBuilderCallable($queryBuilder);
  383.         }
  384.         $paginator $this->container->get(PaginatorFactory::class)->create($queryBuilder);
  385.         return JsonResponse::fromJsonString($paginator->getResultsAsJson());
  386.     }
  387.     public function createIndexQueryBuilder(SearchDto $searchDtoEntityDto $entityDtoFieldCollection $fieldsFilterCollection $filters): QueryBuilder
  388.     {
  389.         return $this->container->get(EntityRepository::class)->createQueryBuilder($searchDto$entityDto$fields$filters);
  390.     }
  391.     public function renderFilters(AdminContext $context): KeyValueStore
  392.     {
  393.         $fields FieldCollection::new($this->configureFields(Crud::PAGE_INDEX));
  394.         $this->container->get(EntityFactory::class)->processFields($context->getEntity(), $fields);
  395.         $filters $this->container->get(FilterFactory::class)->create($context->getCrud()->getFiltersConfig(), $context->getEntity()->getFields(), $context->getEntity());
  396.         /** @var FormInterface&FiltersFormType $filtersForm */
  397.         $filtersForm $this->container->get(FormFactory::class)->createFiltersForm($filters$context->getRequest());
  398.         $formActionParts parse_url($filtersForm->getConfig()->getAction());
  399.         $queryString $formActionParts[EA::QUERY] ?? '';
  400.         parse_str($queryString$queryStringAsArray);
  401.         unset($queryStringAsArray[EA::FILTERS], $queryStringAsArray[EA::PAGE]);
  402.         $responseParameters KeyValueStore::new([
  403.             'templateName' => 'crud/filters',
  404.             'filters_form' => $filtersForm,
  405.             'form_action_query_string_as_array' => $queryStringAsArray,
  406.         ]);
  407.         return $this->configureResponseParameters($responseParameters);
  408.     }
  409.     public function createEntity(string $entityFqcn)
  410.     {
  411.         return new $entityFqcn();
  412.     }
  413.     public function updateEntity(EntityManagerInterface $entityManager$entityInstance): void
  414.     {
  415.         $entityManager->persist($entityInstance);
  416.         $entityManager->flush();
  417.     }
  418.     public function persistEntity(EntityManagerInterface $entityManager$entityInstance): void
  419.     {
  420.         $entityManager->persist($entityInstance);
  421.         $entityManager->flush();
  422.     }
  423.     public function deleteEntity(EntityManagerInterface $entityManager$entityInstance): void
  424.     {
  425.         $entityManager->remove($entityInstance);
  426.         $entityManager->flush();
  427.     }
  428.     public function createEditForm(EntityDto $entityDtoKeyValueStore $formOptionsAdminContext $context): FormInterface
  429.     {
  430.         return $this->createEditFormBuilder($entityDto$formOptions$context)->getForm();
  431.     }
  432.     public function createEditFormBuilder(EntityDto $entityDtoKeyValueStore $formOptionsAdminContext $context): FormBuilderInterface
  433.     {
  434.         return $this->container->get(FormFactory::class)->createEditFormBuilder($entityDto$formOptions$context);
  435.     }
  436.     public function createNewForm(EntityDto $entityDtoKeyValueStore $formOptionsAdminContext $context): FormInterface
  437.     {
  438.         return $this->createNewFormBuilder($entityDto$formOptions$context)->getForm();
  439.     }
  440.     public function createNewFormBuilder(EntityDto $entityDtoKeyValueStore $formOptionsAdminContext $context): FormBuilderInterface
  441.     {
  442.         return $this->container->get(FormFactory::class)->createNewFormBuilder($entityDto$formOptions$context);
  443.     }
  444.     /**
  445.      * Used to add/modify/remove parameters before passing them to the Twig template.
  446.      */
  447.     public function configureResponseParameters(KeyValueStore $responseParameters): KeyValueStore
  448.     {
  449.         return $responseParameters;
  450.     }
  451.     protected function getContext(): ?AdminContext
  452.     {
  453.         return $this->container->get(AdminContextProvider::class)->getContext();
  454.     }
  455.     protected function ajaxEdit(EntityDto $entityDto, ?string $propertyNamebool $newValue): AfterCrudActionEvent
  456.     {
  457.         $this->container->get(EntityUpdater::class)->updateProperty($entityDto$propertyName$newValue);
  458.         $event = new BeforeEntityUpdatedEvent($entityDto->getInstance());
  459.         $this->container->get('event_dispatcher')->dispatch($event);
  460.         $entityInstance $event->getEntityInstance();
  461.         $this->updateEntity($this->container->get('doctrine')->getManagerForClass($entityDto->getFqcn()), $entityInstance);
  462.         $this->container->get('event_dispatcher')->dispatch(new AfterEntityUpdatedEvent($entityInstance));
  463.         $entityDto->setInstance($entityInstance);
  464.         $parameters KeyValueStore::new([
  465.             'action' => Action::EDIT,
  466.             'entity' => $entityDto,
  467.         ]);
  468.         $event = new AfterCrudActionEvent($this->getContext(), $parameters);
  469.         $this->container->get('event_dispatcher')->dispatch($event);
  470.         return $event;
  471.     }
  472.     protected function processUploadedFiles(FormInterface $form): void
  473.     {
  474.         /** @var FormInterface $child */
  475.         foreach ($form as $child) {
  476.             $config $child->getConfig();
  477.             if (!$config->getType()->getInnerType() instanceof FileUploadType) {
  478.                 if ($config->getCompound()) {
  479.                     $this->processUploadedFiles($child);
  480.                 }
  481.                 continue;
  482.             }
  483.             /** @var FileUploadState $state */
  484.             $state $config->getAttribute('state');
  485.             if (!$state->isModified()) {
  486.                 continue;
  487.             }
  488.             $uploadDelete $config->getOption('upload_delete');
  489.             if ($state->hasCurrentFiles() && ($state->isDelete() || (!$state->isAddAllowed() && $state->hasUploadedFiles()))) {
  490.                 foreach ($state->getCurrentFiles() as $file) {
  491.                     $uploadDelete($file);
  492.                 }
  493.                 $state->setCurrentFiles([]);
  494.             }
  495.             $filePaths = (array) $child->getData();
  496.             $uploadDir $config->getOption('upload_dir');
  497.             $uploadNew $config->getOption('upload_new');
  498.             foreach ($state->getUploadedFiles() as $index => $file) {
  499.                 $fileName u($filePaths[$index])->replace($uploadDir'')->toString();
  500.                 $uploadNew($file$uploadDir$fileName);
  501.             }
  502.         }
  503.     }
  504.     protected function getRedirectResponseAfterSave(AdminContext $contextstring $action): RedirectResponse
  505.     {
  506.         $submitButtonName $context->getRequest()->request->all()['ea']['newForm']['btn'];
  507.         if (Action::SAVE_AND_CONTINUE === $submitButtonName) {
  508.             $url $this->container->get(AdminUrlGenerator::class)
  509.                 ->setAction(Action::EDIT)
  510.                 ->setEntityId($context->getEntity()->getPrimaryKeyValue())
  511.                 ->generateUrl();
  512.             return $this->redirect($url);
  513.         }
  514.         if (Action::SAVE_AND_RETURN === $submitButtonName) {
  515.             $url $context->getReferrer()
  516.                 ?? $this->container->get(AdminUrlGenerator::class)->setAction(Action::INDEX)->generateUrl();
  517.             return $this->redirect($url);
  518.         }
  519.         if (Action::SAVE_AND_ADD_ANOTHER === $submitButtonName) {
  520.             $url $this->container->get(AdminUrlGenerator::class)->setAction(Action::NEW)->generateUrl();
  521.             return $this->redirect($url);
  522.         }
  523.         return $this->redirectToRoute($context->getDashboardRouteName());
  524.     }
  525.     protected function getFieldAssets(FieldCollection $fieldDtos): AssetsDto
  526.     {
  527.         $fieldAssetsDto = new AssetsDto();
  528.         $currentPageName $this->getContext()?->getCrud()?->getCurrentPage();
  529.         foreach ($fieldDtos as $fieldDto) {
  530.             $fieldAssetsDto $fieldAssetsDto->mergeWith($fieldDto->getAssets()->loadedOn($currentPageName));
  531.         }
  532.         return $fieldAssetsDto;
  533.     }
  534. }