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

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