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

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.             // cast to integer instead of string to avoid sending empty responses for 'false'
  214.             return new Response((int) $newValue);
  215.         }
  216.         $editForm $this->createEditForm($context->getEntity(), $context->getCrud()->getEditFormOptions(), $context);
  217.         $editForm->handleRequest($context->getRequest());
  218.         if ($editForm->isSubmitted() && $editForm->isValid()) {
  219.             $this->processUploadedFiles($editForm);
  220.             $event = new BeforeEntityUpdatedEvent($entityInstance);
  221.             $this->container->get('event_dispatcher')->dispatch($event);
  222.             $entityInstance $event->getEntityInstance();
  223.             $this->updateEntity($this->container->get('doctrine')->getManagerForClass($context->getEntity()->getFqcn()), $entityInstance);
  224.             $this->container->get('event_dispatcher')->dispatch(new AfterEntityUpdatedEvent($entityInstance));
  225.             return $this->getRedirectResponseAfterSave($contextAction::EDIT);
  226.         }
  227.         $responseParameters $this->configureResponseParameters(KeyValueStore::new([
  228.             'pageName' => Crud::PAGE_EDIT,
  229.             'templateName' => 'crud/edit',
  230.             'edit_form' => $editForm,
  231.             'entity' => $context->getEntity(),
  232.         ]));
  233.         $event = new AfterCrudActionEvent($context$responseParameters);
  234.         $this->container->get('event_dispatcher')->dispatch($event);
  235.         if ($event->isPropagationStopped()) {
  236.             return $event->getResponse();
  237.         }
  238.         return $responseParameters;
  239.     }
  240.     public function new(AdminContext $context)
  241.     {
  242.         $event = new BeforeCrudActionEvent($context);
  243.         $this->container->get('event_dispatcher')->dispatch($event);
  244.         if ($event->isPropagationStopped()) {
  245.             return $event->getResponse();
  246.         }
  247.         if (!$this->isGranted(Permission::EA_EXECUTE_ACTION, ['action' => Action::NEW, 'entity' => null])) {
  248.             throw new ForbiddenActionException($context);
  249.         }
  250.         if (!$context->getEntity()->isAccessible()) {
  251.             throw new InsufficientEntityPermissionException($context);
  252.         }
  253.         $context->getEntity()->setInstance($this->createEntity($context->getEntity()->getFqcn()));
  254.         $this->container->get(EntityFactory::class)->processFields($context->getEntity(), FieldCollection::new($this->configureFields(Crud::PAGE_NEW)));
  255.         $context->getCrud()->setFieldAssets($this->getFieldAssets($context->getEntity()->getFields()));
  256.         $this->container->get(EntityFactory::class)->processActions($context->getEntity(), $context->getCrud()->getActionsConfig());
  257.         $newForm $this->createNewForm($context->getEntity(), $context->getCrud()->getNewFormOptions(), $context);
  258.         $newForm->handleRequest($context->getRequest());
  259.         $entityInstance $newForm->getData();
  260.         $context->getEntity()->setInstance($entityInstance);
  261.         if ($newForm->isSubmitted() && $newForm->isValid()) {
  262.             $this->processUploadedFiles($newForm);
  263.             $event = new BeforeEntityPersistedEvent($entityInstance);
  264.             $this->container->get('event_dispatcher')->dispatch($event);
  265.             $entityInstance $event->getEntityInstance();
  266.             $this->persistEntity($this->container->get('doctrine')->getManagerForClass($context->getEntity()->getFqcn()), $entityInstance);
  267.             $this->container->get('event_dispatcher')->dispatch(new AfterEntityPersistedEvent($entityInstance));
  268.             $context->getEntity()->setInstance($entityInstance);
  269.             return $this->getRedirectResponseAfterSave($contextAction::NEW);
  270.         }
  271.         $responseParameters $this->configureResponseParameters(KeyValueStore::new([
  272.             'pageName' => Crud::PAGE_NEW,
  273.             'templateName' => 'crud/new',
  274.             'entity' => $context->getEntity(),
  275.             'new_form' => $newForm,
  276.         ]));
  277.         $event = new AfterCrudActionEvent($context$responseParameters);
  278.         $this->container->get('event_dispatcher')->dispatch($event);
  279.         if ($event->isPropagationStopped()) {
  280.             return $event->getResponse();
  281.         }
  282.         return $responseParameters;
  283.     }
  284.     public function delete(AdminContext $context)
  285.     {
  286.         $event = new BeforeCrudActionEvent($context);
  287.         $this->container->get('event_dispatcher')->dispatch($event);
  288.         if ($event->isPropagationStopped()) {
  289.             return $event->getResponse();
  290.         }
  291.         if (!$this->isGranted(Permission::EA_EXECUTE_ACTION, ['action' => Action::DELETE'entity' => $context->getEntity()])) {
  292.             throw new ForbiddenActionException($context);
  293.         }
  294.         if (!$context->getEntity()->isAccessible()) {
  295.             throw new InsufficientEntityPermissionException($context);
  296.         }
  297.         $csrfToken $context->getRequest()->request->get('token');
  298.         if ($this->container->has('security.csrf.token_manager') && !$this->isCsrfTokenValid('ea-delete'$csrfToken)) {
  299.             return $this->redirectToRoute($context->getDashboardRouteName());
  300.         }
  301.         $entityInstance $context->getEntity()->getInstance();
  302.         $event = new BeforeEntityDeletedEvent($entityInstance);
  303.         $this->container->get('event_dispatcher')->dispatch($event);
  304.         if ($event->isPropagationStopped()) {
  305.             return $event->getResponse();
  306.         }
  307.         $entityInstance $event->getEntityInstance();
  308.         try {
  309.             $this->deleteEntity($this->container->get('doctrine')->getManagerForClass($context->getEntity()->getFqcn()), $entityInstance);
  310.         } catch (ForeignKeyConstraintViolationException $e) {
  311.             throw new EntityRemoveException(['entity_name' => $context->getEntity()->getName(), 'message' => $e->getMessage()]);
  312.         }
  313.         $this->container->get('event_dispatcher')->dispatch(new AfterEntityDeletedEvent($entityInstance));
  314.         $responseParameters $this->configureResponseParameters(KeyValueStore::new([
  315.             'entity' => $context->getEntity(),
  316.         ]));
  317.         $event = new AfterCrudActionEvent($context$responseParameters);
  318.         $this->container->get('event_dispatcher')->dispatch($event);
  319.         if ($event->isPropagationStopped()) {
  320.             return $event->getResponse();
  321.         }
  322.         if (null !== $referrer $context->getReferrer()) {
  323.             return $this->redirect($referrer);
  324.         }
  325.         return $this->redirect($this->container->get(AdminUrlGenerator::class)->setAction(Action::INDEX)->unset(EA::ENTITY_ID)->generateUrl());
  326.     }
  327.     public function batchDelete(AdminContext $contextBatchActionDto $batchActionDto): Response
  328.     {
  329.         $event = new BeforeCrudActionEvent($context);
  330.         $this->container->get('event_dispatcher')->dispatch($event);
  331.         if ($event->isPropagationStopped()) {
  332.             return $event->getResponse();
  333.         }
  334.         if (!$this->isCsrfTokenValid('ea-batch-action-'.Action::BATCH_DELETE$batchActionDto->getCsrfToken())) {
  335.             return $this->redirectToRoute($context->getDashboardRouteName());
  336.         }
  337.         $entityManager $this->container->get('doctrine')->getManagerForClass($batchActionDto->getEntityFqcn());
  338.         $repository $entityManager->getRepository($batchActionDto->getEntityFqcn());
  339.         foreach ($batchActionDto->getEntityIds() as $entityId) {
  340.             $entityInstance $repository->find($entityId);
  341.             if (!$entityInstance) {
  342.                 continue;
  343.             }
  344.             $entityDto $context->getEntity()->newWithInstance($entityInstance);
  345.             if (!$this->isGranted(Permission::EA_EXECUTE_ACTION, ['action' => Action::DELETE'entity' => $entityDto])) {
  346.                 throw new ForbiddenActionException($context);
  347.             }
  348.             if (!$entityDto->isAccessible()) {
  349.                 throw new InsufficientEntityPermissionException($context);
  350.             }
  351.             $event = new BeforeEntityDeletedEvent($entityInstance);
  352.             $this->container->get('event_dispatcher')->dispatch($event);
  353.             $entityInstance $event->getEntityInstance();
  354.             try {
  355.                 $this->deleteEntity($entityManager$entityInstance);
  356.             } catch (ForeignKeyConstraintViolationException $e) {
  357.                 throw new EntityRemoveException(['entity_name' => $entityDto->toString(), 'message' => $e->getMessage()]);
  358.             }
  359.             $this->container->get('event_dispatcher')->dispatch(new AfterEntityDeletedEvent($entityInstance));
  360.         }
  361.         $responseParameters $this->configureResponseParameters(KeyValueStore::new([
  362.             'entity' => $context->getEntity(),
  363.             'batchActionDto' => $batchActionDto,
  364.         ]));
  365.         $event = new AfterCrudActionEvent($context$responseParameters);
  366.         $this->container->get('event_dispatcher')->dispatch($event);
  367.         if ($event->isPropagationStopped()) {
  368.             return $event->getResponse();
  369.         }
  370.         return $this->redirect($batchActionDto->getReferrerUrl());
  371.     }
  372.     public function autocomplete(AdminContext $context): JsonResponse
  373.     {
  374.         $queryBuilder $this->createIndexQueryBuilder($context->getSearch(), $context->getEntity(), FieldCollection::new([]), FilterCollection::new());
  375.         $autocompleteContext $context->getRequest()->get(AssociationField::PARAM_AUTOCOMPLETE_CONTEXT);
  376.         /** @var CrudControllerInterface $controller */
  377.         $controller $this->container->get(ControllerFactory::class)->getCrudControllerInstance($autocompleteContext[EA::CRUD_CONTROLLER_FQCN], Action::INDEX$context->getRequest());
  378.         /** @var FieldDto $field */
  379.         $field FieldCollection::new($controller->configureFields($autocompleteContext['originatingPage']))->getByProperty($autocompleteContext['propertyName']);
  380.         /** @var \Closure|null $queryBuilderCallable */
  381.         $queryBuilderCallable $field->getCustomOption(AssociationField::OPTION_QUERY_BUILDER_CALLABLE);
  382.         if (null !== $queryBuilderCallable) {
  383.             $queryBuilderCallable($queryBuilder);
  384.         }
  385.         $paginator $this->container->get(PaginatorFactory::class)->create($queryBuilder);
  386.         return JsonResponse::fromJsonString($paginator->getResultsAsJson());
  387.     }
  388.     public function createIndexQueryBuilder(SearchDto $searchDtoEntityDto $entityDtoFieldCollection $fieldsFilterCollection $filters): QueryBuilder
  389.     {
  390.         return $this->container->get(EntityRepository::class)->createQueryBuilder($searchDto$entityDto$fields$filters);
  391.     }
  392.     public function renderFilters(AdminContext $context): KeyValueStore
  393.     {
  394.         $fields FieldCollection::new($this->configureFields(Crud::PAGE_INDEX));
  395.         $this->container->get(EntityFactory::class)->processFields($context->getEntity(), $fields);
  396.         $filters $this->container->get(FilterFactory::class)->create($context->getCrud()->getFiltersConfig(), $context->getEntity()->getFields(), $context->getEntity());
  397.         /** @var FiltersFormType $filtersForm */
  398.         $filtersForm $this->container->get(FormFactory::class)->createFiltersForm($filters$context->getRequest());
  399.         $formActionParts parse_url($filtersForm->getConfig()->getAction());
  400.         $queryString $formActionParts[EA::QUERY] ?? '';
  401.         parse_str($queryString$queryStringAsArray);
  402.         unset($queryStringAsArray[EA::FILTERS], $queryStringAsArray[EA::PAGE]);
  403.         $responseParameters KeyValueStore::new([
  404.             'templateName' => 'crud/filters',
  405.             'filters_form' => $filtersForm,
  406.             'form_action_query_string_as_array' => $queryStringAsArray,
  407.         ]);
  408.         return $this->configureResponseParameters($responseParameters);
  409.     }
  410.     public function createEntity(string $entityFqcn)
  411.     {
  412.         return new $entityFqcn();
  413.     }
  414.     public function updateEntity(EntityManagerInterface $entityManager$entityInstance): void
  415.     {
  416.         $entityManager->persist($entityInstance);
  417.         $entityManager->flush();
  418.     }
  419.     public function persistEntity(EntityManagerInterface $entityManager$entityInstance): void
  420.     {
  421.         $entityManager->persist($entityInstance);
  422.         $entityManager->flush();
  423.     }
  424.     public function deleteEntity(EntityManagerInterface $entityManager$entityInstance): void
  425.     {
  426.         $entityManager->remove($entityInstance);
  427.         $entityManager->flush();
  428.     }
  429.     public function createEditForm(EntityDto $entityDtoKeyValueStore $formOptionsAdminContext $context): FormInterface
  430.     {
  431.         return $this->createEditFormBuilder($entityDto$formOptions$context)->getForm();
  432.     }
  433.     public function createEditFormBuilder(EntityDto $entityDtoKeyValueStore $formOptionsAdminContext $context): FormBuilderInterface
  434.     {
  435.         return $this->container->get(FormFactory::class)->createEditFormBuilder($entityDto$formOptions$context);
  436.     }
  437.     public function createNewForm(EntityDto $entityDtoKeyValueStore $formOptionsAdminContext $context): FormInterface
  438.     {
  439.         return $this->createNewFormBuilder($entityDto$formOptions$context)->getForm();
  440.     }
  441.     public function createNewFormBuilder(EntityDto $entityDtoKeyValueStore $formOptionsAdminContext $context): FormBuilderInterface
  442.     {
  443.         return $this->container->get(FormFactory::class)->createNewFormBuilder($entityDto$formOptions$context);
  444.     }
  445.     /**
  446.      * Used to add/modify/remove parameters before passing them to the Twig template.
  447.      */
  448.     public function configureResponseParameters(KeyValueStore $responseParameters): KeyValueStore
  449.     {
  450.         return $responseParameters;
  451.     }
  452.     protected function getContext(): ?AdminContext
  453.     {
  454.         return $this->container->get(AdminContextProvider::class)->getContext();
  455.     }
  456.     protected function ajaxEdit(EntityDto $entityDto, ?string $propertyNamebool $newValue): AfterCrudActionEvent
  457.     {
  458.         $this->container->get(EntityUpdater::class)->updateProperty($entityDto$propertyName$newValue);
  459.         $event = new BeforeEntityUpdatedEvent($entityDto->getInstance());
  460.         $this->container->get('event_dispatcher')->dispatch($event);
  461.         $entityInstance $event->getEntityInstance();
  462.         $this->updateEntity($this->container->get('doctrine')->getManagerForClass($entityDto->getFqcn()), $entityInstance);
  463.         $this->container->get('event_dispatcher')->dispatch(new AfterEntityUpdatedEvent($entityInstance));
  464.         $entityDto->setInstance($entityInstance);
  465.         $parameters KeyValueStore::new([
  466.             'action' => Action::EDIT,
  467.             'entity' => $entityDto,
  468.         ]);
  469.         $event = new AfterCrudActionEvent($this->getContext(), $parameters);
  470.         $this->container->get('event_dispatcher')->dispatch($event);
  471.         return $event;
  472.     }
  473.     protected function processUploadedFiles(FormInterface $form): void
  474.     {
  475.         /** @var FormInterface $child */
  476.         foreach ($form as $child) {
  477.             $config $child->getConfig();
  478.             if (!$config->getType()->getInnerType() instanceof FileUploadType) {
  479.                 if ($config->getCompound()) {
  480.                     $this->processUploadedFiles($child);
  481.                 }
  482.                 continue;
  483.             }
  484.             /** @var FileUploadState $state */
  485.             $state $config->getAttribute('state');
  486.             if (!$state->isModified()) {
  487.                 continue;
  488.             }
  489.             $uploadDelete $config->getOption('upload_delete');
  490.             if ($state->hasCurrentFiles() && ($state->isDelete() || (!$state->isAddAllowed() && $state->hasUploadedFiles()))) {
  491.                 foreach ($state->getCurrentFiles() as $file) {
  492.                     $uploadDelete($file);
  493.                 }
  494.                 $state->setCurrentFiles([]);
  495.             }
  496.             $filePaths = (array) $child->getData();
  497.             $uploadDir $config->getOption('upload_dir');
  498.             $uploadNew $config->getOption('upload_new');
  499.             foreach ($state->getUploadedFiles() as $index => $file) {
  500.                 $fileName u($filePaths[$index])->replace($uploadDir'')->toString();
  501.                 $uploadNew($file$uploadDir$fileName);
  502.             }
  503.         }
  504.     }
  505.     protected function getRedirectResponseAfterSave(AdminContext $contextstring $action): RedirectResponse
  506.     {
  507.         $submitButtonName $context->getRequest()->request->all()['ea']['newForm']['btn'];
  508.         if (Action::SAVE_AND_CONTINUE === $submitButtonName) {
  509.             $url $this->container->get(AdminUrlGenerator::class)
  510.                 ->setAction(Action::EDIT)
  511.                 ->setEntityId($context->getEntity()->getPrimaryKeyValue())
  512.                 ->generateUrl();
  513.             return $this->redirect($url);
  514.         }
  515.         if (Action::SAVE_AND_RETURN === $submitButtonName) {
  516.             $url $context->getReferrer()
  517.                 ?? $this->container->get(AdminUrlGenerator::class)->setAction(Action::INDEX)->generateUrl();
  518.             return $this->redirect($url);
  519.         }
  520.         if (Action::SAVE_AND_ADD_ANOTHER === $submitButtonName) {
  521.             $url $this->container->get(AdminUrlGenerator::class)->setAction(Action::NEW)->generateUrl();
  522.             return $this->redirect($url);
  523.         }
  524.         return $this->redirectToRoute($context->getDashboardRouteName());
  525.     }
  526.     protected function getFieldAssets(FieldCollection $fieldDtos): AssetsDto
  527.     {
  528.         $fieldAssetsDto = new AssetsDto();
  529.         $currentPageName $this->getContext()?->getCrud()?->getCurrentPage();
  530.         foreach ($fieldDtos as $fieldDto) {
  531.             $fieldAssetsDto $fieldAssetsDto->mergeWith($fieldDto->getAssets()->loadedOn($currentPageName));
  532.         }
  533.         return $fieldAssetsDto;
  534.     }
  535. }