You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

864 satır
32KB

  1. <?php
  2. namespace Lc\SovBundle\Controller;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Doctrine\ORM\QueryBuilder;
  5. use EasyCorp\Bundle\EasyAdminBundle\Collection\ActionCollection;
  6. use EasyCorp\Bundle\EasyAdminBundle\Collection\EntityCollection;
  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\Crud;
  12. use EasyCorp\Bundle\EasyAdminBundle\Config\KeyValueStore;
  13. use EasyCorp\Bundle\EasyAdminBundle\Config\Option\EA;
  14. use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
  15. use EasyCorp\Bundle\EasyAdminBundle\Contracts\Controller\CrudControllerInterface;
  16. use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController as EaAbstractCrudController;
  17. use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
  18. use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
  19. use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
  20. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
  21. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  22. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  23. use EasyCorp\Bundle\EasyAdminBundle\Exception\ForbiddenActionException;
  24. use EasyCorp\Bundle\EasyAdminBundle\Exception\InsufficientEntityPermissionException;
  25. use EasyCorp\Bundle\EasyAdminBundle\Factory\ControllerFactory;
  26. use EasyCorp\Bundle\EasyAdminBundle\Factory\EntityFactory;
  27. use EasyCorp\Bundle\EasyAdminBundle\Factory\FilterFactory;
  28. use EasyCorp\Bundle\EasyAdminBundle\Factory\PaginatorFactory;
  29. use EasyCorp\Bundle\EasyAdminBundle\Field\AssociationField;
  30. use EasyCorp\Bundle\EasyAdminBundle\Field\FormField;
  31. use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
  32. use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
  33. use EasyCorp\Bundle\EasyAdminBundle\Provider\AdminContextProvider;
  34. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  35. use EasyCorp\Bundle\EasyAdminBundle\Security\Permission;
  36. use Lc\SovBundle\Component\EntityComponent;
  37. use Lc\SovBundle\Definition\ActionDefinition;
  38. use Lc\SovBundle\Doctrine\Extension\DevAliasInterface;
  39. use Lc\SovBundle\Doctrine\Extension\SeoInterface;
  40. use Lc\SovBundle\Doctrine\Extension\SortableInterface;
  41. use Lc\SovBundle\Doctrine\Extension\StatusInterface;
  42. use Lc\SovBundle\Doctrine\Extension\TranslatableInterface;
  43. use Lc\SovBundle\Doctrine\Extension\TreeInterface;
  44. use Lc\SovBundle\Field\CollectionField;
  45. use Lc\SovBundle\Form\Common\FiltersFormType;
  46. use Lc\SovBundle\Form\Common\PositionType;
  47. use Lc\SovBundle\Repository\EntityRepository;
  48. use Lc\SovBundle\Repository\RepositoryQueryInterface;
  49. use Lc\SovBundle\Translation\TranslatorAdmin;
  50. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  51. use Symfony\Component\Form\Extension\Core\Type\TextType;
  52. use Symfony\Component\Form\FormInterface;
  53. use Symfony\Component\HttpFoundation\JsonResponse;
  54. use Symfony\Component\HttpFoundation\Response;
  55. abstract class AbstractAdminController extends EaAbstractCrudController
  56. {
  57. use ControllerTrait;
  58. protected FormInterface $filtersForm;
  59. protected TranslatorAdmin $translatorAdmin;
  60. protected bool $isRepositoryQueryFiltered = false;
  61. abstract public function getRepositoryQuery(): RepositoryQueryInterface;
  62. public function configureResponseParameters(KeyValueStore $responseParameters): KeyValueStore
  63. {
  64. if ($responseParameters->get('global_actions')) {
  65. $this->overrideGlobalActions($responseParameters->get('global_actions'));
  66. }
  67. if ($responseParameters->get('entities')) {
  68. $this->overrideEntitiesActions($responseParameters->get('entities'), $responseParameters->get('pageName'));
  69. }
  70. if (Crud::PAGE_INDEX === $responseParameters->get('pageName')) {
  71. $responseParameters->set('fields', $this->configureFields('index'));
  72. if (isset($this->filtersForm)) {
  73. $responseParameters->set('filters_form', $this->filtersForm);
  74. }
  75. }
  76. $responseParameters->set('translation_entity_name', $this->getTranslationEntityName());
  77. return $responseParameters;
  78. }
  79. public function getTranslationEntityName()
  80. {
  81. return $this->getEntityFqcn();
  82. }
  83. public function overrideEntitiesActions(?EntityCollection $entities, string $pageName): void
  84. {
  85. }
  86. public function overrideGlobalActions(?ActionCollection $actions): void
  87. {
  88. if ($actions) {
  89. $context = $this->getAdminContextProvider()->getContext();
  90. $adminUrlGenerator = $this->getAdminUrlGenerator();
  91. foreach ($actions as $i => $action) {
  92. //récriture du bouton 'retour au parent'
  93. if ($action->getName() == 'index_parent') {
  94. $entity = $context->getEntity()->getInstance();
  95. if ($entity !== null) {
  96. if ($entity->getParent() !== null) {
  97. $url = $adminUrlGenerator
  98. ->setController($context->getCrud()->getControllerFqcn())
  99. ->set('entityId', $entity->getParent()->getId())
  100. ->generateUrl();
  101. $action->setLinkUrl($url);
  102. }
  103. } else {
  104. unset($actions[$i]);
  105. }
  106. }
  107. if ($action->getName() == 'sort') {
  108. $entityId = $context->getRequest()->get('entityId');
  109. if ($entityId != null) {
  110. $url = $adminUrlGenerator
  111. ->setController($context->getCrud()->getControllerFqcn())
  112. ->setAction($action->getName())
  113. ->set('entityId', $entityId)
  114. ->generateUrl();
  115. $action->setLinkUrl($url);
  116. }
  117. }
  118. if ($action->getName() == ActionDefinition::WRITE_TO_USER) {
  119. $entity = $context->getEntity()->getInstance();
  120. if ($entity !== null) {
  121. if (method_exists($entity, 'getUser')) {
  122. $url = $this->generateEaUrl(UserA)->setController($context->getCrud()->getControllerFqcn())
  123. ->set('entityId', $entity->getParent()->getId())
  124. ->generateUrl();
  125. $action->setLinkUrl($url);
  126. }
  127. } else {
  128. unset($actions[$i]);
  129. }
  130. }
  131. }
  132. }
  133. }
  134. protected function getRequestCrudAction(): string
  135. {
  136. return $this->getRequestStack()->getCurrentRequest()->get('crudAction');
  137. }
  138. public function configureCrud(Crud $crud): Crud
  139. {
  140. $crud = parent::configureCrud($crud);
  141. if ($this->getRequestCrudAction() === ActionDefinition::SORT) {
  142. $crud->setPaginatorPageSize(9999);
  143. } else {
  144. $this->setMaxResults($crud);
  145. }
  146. $crud->setFormOptions(['translation_entity_name' => $this->getTranslationEntityName()]);
  147. if ($this->isInstanceOf(SortableInterface::class)) {
  148. $crud->setDefaultSort(['position' => 'ASC']);
  149. } else {
  150. $crud->setDefaultSort(['id' => 'DESC']);
  151. }
  152. return $crud;
  153. }
  154. public function setMaxResults(Crud $crud): void
  155. {
  156. $entityClass = $this->getEntityFqcn();
  157. $paramListMaxResults = 'listMaxResults';
  158. $paramSessionListMaxResults = $entityClass . '-' . $paramListMaxResults;
  159. $requestListMaxResults = $this->getRequestStack()->getCurrentRequest()->get($paramListMaxResults);
  160. if ($requestListMaxResults) {
  161. $this->getRequestStack()->getSession()->set($paramSessionListMaxResults, $requestListMaxResults);
  162. }
  163. $maxResults = $this->getRequestStack()->getSession()->get($paramSessionListMaxResults) ? $this->get('session')->get(
  164. $paramSessionListMaxResults
  165. ) : 30;
  166. $crud->setPaginatorPageSize($maxResults);
  167. }
  168. public function getSeoPanel(): ?array
  169. {
  170. if ($this->isInstanceOf(SeoInterface::class)) {
  171. return [
  172. FormField::addPanel('seo')->setTemplateName('crud/field/generic'),
  173. TextField::new('metaTitle')->setLabel('Meta Title')->setHelp(
  174. 'Affiché dans les résultats de recherche Google'
  175. )->hideOnIndex(),
  176. TextareaField::new('metaDescription')->setLabel('Meta description')->setHelp(
  177. 'Affiché dans les résultats de recherche Google'
  178. )->hideOnIndex(),
  179. CollectionField::new('oldUrls')
  180. ->setFormTypeOption('entry_type', TextType::class)->setLabel(
  181. 'Anciennes urls du document'
  182. )->hideOnIndex(),
  183. ];
  184. } else {
  185. return null;
  186. }
  187. }
  188. public function getConfPanel(): ?array
  189. {
  190. if ($this->isInstanceOf(DevAliasInterface::class)) {
  191. return [
  192. FormField::addPanel('configuration')->setTemplateName('crud/field/generic'),
  193. TextField::new('devAlias')->hideOnIndex(),
  194. ];
  195. } else {
  196. return null;
  197. }
  198. }
  199. public function sort(AdminContext $context)
  200. {
  201. $event = new BeforeCrudActionEvent($context);
  202. $this->container->get('event_dispatcher')->dispatch($event);
  203. if ($event->isPropagationStopped()) {
  204. return $event->getResponse();
  205. }
  206. //if (!$this->isGranted(Permission::EA_EXECUTE_ACTION) || !$this->isInstanceOf(SortableInterface::class)) {
  207. if (!$this->isInstanceOf(SortableInterface::class)) {
  208. throw new ForbiddenActionException($context);
  209. }
  210. $fields = FieldCollection::new($this->configureFields(Crud::PAGE_INDEX));
  211. $filters = $this->container->get(FilterFactory::class)->create(
  212. $context->getCrud()->getFiltersConfig(),
  213. $fields,
  214. $context->getEntity()
  215. );
  216. $queryBuilder = $this->createSortQueryBuilder($context->getSearch(), $context->getEntity(), $fields, $filters);
  217. $paginator = $this->container->get(PaginatorFactory::class)->create($queryBuilder);
  218. $entities = $this->container->get(EntityFactory::class)->createCollection($context->getEntity(), $paginator->getResults());
  219. $this->container->get(EntityFactory::class)->processFieldsForAll($entities, $fields);
  220. $sortableForm = $this->createFormBuilder(array('entities', $paginator->getResults()))
  221. ->add(
  222. 'entities',
  223. CollectionType::class,
  224. array(
  225. 'required' => true,
  226. 'allow_add' => true,
  227. 'entry_type' => PositionType::class,
  228. )
  229. )
  230. ->getForm();
  231. $entityManager = $this->container->get('doctrine')->getManagerForClass($this->getEntityFqcn());
  232. $repository = $entityManager->getRepository($this->getEntityFqcn());
  233. $sortableForm->handleRequest($context->getRequest());
  234. if ($sortableForm->isSubmitted() && $sortableForm->isValid()) {
  235. foreach ($sortableForm->get('entities')->getData() as $elm) {
  236. $entityInstance = $repository->find($elm['id']);
  237. $entityDto = $context->getEntity()->newWithInstance($entityInstance);
  238. if (!$entityDto->isAccessible()) {
  239. throw new InsufficientEntityPermissionException($context);
  240. }
  241. $event = new BeforeEntityUpdatedEvent($entityInstance);
  242. $this->container->get('event_dispatcher')->dispatch($event);
  243. $entityInstance = $event->getEntityInstance();
  244. $entityInstance->setPosition($elm['position']);
  245. $this->updateEntity($entityManager, $entityInstance);
  246. // @TODO : ce dispatch déclenche UpdateProductfamilyAfterFlushEventSubscriber dans Caracole et on tombe sur une erreur "Maximum execution time"
  247. //$this->get('event_dispatcher')->dispatch(new AfterEntityUpdatedEvent($entityInstance));
  248. }
  249. $url = $this->container->get(AdminUrlGenerator::class)
  250. ->setAction(ActionDefinition::INDEX)
  251. ->generateUrl();
  252. $this->addFlashTranslator('success', 'sorted');
  253. return $this->redirect($url);
  254. }
  255. $responseParameters = $this->configureResponseParameters(
  256. KeyValueStore::new(
  257. [
  258. 'pageName' => Crud::PAGE_INDEX,
  259. 'templatePath' => '@LcSov/adminlte/crud/sort.html.twig',
  260. 'entities' => $entities,
  261. 'paginator' => $paginator,
  262. 'global_actions' => array(),
  263. 'batch_actions' => array(),
  264. 'filters' => $filters,
  265. 'sortable_form' => $sortableForm,
  266. ]
  267. )
  268. );
  269. $responseParameters->set('fields', $this->configureFields('index'));
  270. $event = new AfterCrudActionEvent($context, $responseParameters);
  271. $this->container->get('event_dispatcher')->dispatch($event);
  272. if ($event->isPropagationStopped()) {
  273. return $event->getResponse();
  274. }
  275. return $responseParameters;
  276. }
  277. public function duplicate(
  278. AdminContext $context,
  279. EntityComponent $entityComponent,
  280. TranslatorAdmin $translatorAdmin,
  281. EntityManagerInterface $em
  282. )
  283. {
  284. if (!$this->isGranted(
  285. Permission::EA_EXECUTE_ACTION,
  286. ['action' => ActionDefinition::DUPLICATE, 'entity' => $context->getEntity()]
  287. )) {
  288. throw new ForbiddenActionException($context);
  289. }
  290. if (!$context->getEntity()->isAccessible()) {
  291. throw new InsufficientEntityPermissionException($context);
  292. }
  293. $newEntity = $entityComponent->duplicateEntity($context->getEntity()->getInstance());
  294. $em->create($newEntity, false);
  295. $em->flush();
  296. $url = $this->get(AdminUrlGenerator::class)
  297. ->setAction(ActionDefinition::EDIT)
  298. ->setEntityId($newEntity->getId())
  299. ->generateUrl();
  300. $this->addFlashTranslator('success', ActionDefinition::DUPLICATE);
  301. return $this->redirect($url);
  302. }
  303. public function isRepositoryQueryFiltered(): bool
  304. {
  305. if (($this->filtersForm && $this->filtersForm->isSubmitted()) || $this->isRepositoryQueryFiltered) {
  306. return true;
  307. } else {
  308. return false;
  309. }
  310. }
  311. public function createIndexRepositoryQuery(
  312. SearchDto $searchDto,
  313. EntityDto $entityDto,
  314. FieldCollection $fields,
  315. FilterCollection $filters
  316. ): RepositoryQueryInterface
  317. {
  318. $repositoryQuery = $this->container->get(EntityRepository::class)->createRepositoryQuery(
  319. $this->getRepositoryQuery(),
  320. $searchDto,
  321. $entityDto,
  322. $fields,
  323. $filters
  324. );
  325. // TODO : déplacer dans EntotyRepository
  326. if ($this->isInstanceOf(TreeInterface::class)) {
  327. if ($entityDto->getInstance()) {
  328. $repositoryQuery->filterByParent($entityDto->getInstance());
  329. } else {
  330. $repositoryQuery->filterIsParent();
  331. }
  332. }
  333. if ($this->isInstanceOf(StatusInterface::class)) {
  334. $repositoryQuery->filterIsOnlineAndOffline();
  335. }
  336. $this->filtersForm = $this->createForm(
  337. FiltersFormType::class,
  338. null,
  339. array(
  340. 'fields' => $fields,
  341. 'entity_dto' => $entityDto,
  342. 'entity_class' => $this->getEntityFqcn(),
  343. 'entity_name' => $entityDto->getName(),
  344. )
  345. );
  346. $filterManager = $this->getFilterManager();
  347. $this->filtersForm->handleRequest($searchDto->getRequest());
  348. $this->isRepositoryQueryFiltered = $filterManager->handleFiltersForm($repositoryQuery, $this->filtersForm, $fields, $entityDto);
  349. return $repositoryQuery;
  350. }
  351. public function createSortRepositoryQuery(
  352. SearchDto $searchDto,
  353. EntityDto $entityDto,
  354. FieldCollection $fields,
  355. FilterCollection $filters
  356. ): RepositoryQueryInterface
  357. {
  358. $repositoryQuery = $this->createIndexRepositoryQuery($searchDto, $entityDto, $fields, $filters);
  359. if ($this->isInstanceOf(StatusInterface::class)) {
  360. $repositoryQuery->filterIsOnline();
  361. }
  362. $repositoryQuery->orderBy('position', 'asc');
  363. return $repositoryQuery;
  364. }
  365. public function createIndexQueryBuilder(
  366. SearchDto $searchDto,
  367. EntityDto $entityDto,
  368. FieldCollection $fields,
  369. FilterCollection $filters
  370. ): QueryBuilder
  371. {
  372. $repositoryQuery = $this->createIndexRepositoryQuery($searchDto, $entityDto, $fields, $filters);
  373. return $repositoryQuery->getQueryBuilder();
  374. }
  375. public function createSortQueryBuilder(
  376. SearchDto $searchDto,
  377. EntityDto $entityDto,
  378. FieldCollection $fields,
  379. FilterCollection $filters
  380. ): QueryBuilder
  381. {
  382. $repositoryQuery = $this->createSortRepositoryQuery($searchDto, $entityDto, $fields, $filters);
  383. return $repositoryQuery->getQueryBuilder();
  384. }
  385. public function edit(AdminContext $context)
  386. {
  387. $response = parent::edit($context);;
  388. // on vide le flash bag si édition en ajax (notification déjà affichée en Javascript)
  389. if ($context->getRequest()->isXmlHttpRequest()) {
  390. $this->get('session')->getFlashBag()->clear();
  391. }
  392. return $response;
  393. }
  394. public function getControllerFqcnByInterface(string $interface): string
  395. {
  396. $context = $this->get(AdminContextProvider::class)->getContext();
  397. return $context->getCrudControllers()->findCrudFqcnByEntityFqcn(
  398. $this->get(EntityManagerInterface::class)->getEntityName($interface)
  399. );
  400. }
  401. public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
  402. {
  403. $entityManager->update($entityInstance);
  404. $entityManager->flush();
  405. $this->getFlashBagTranslator()->add('success', 'updated', $this->getTranslationEntityName());
  406. }
  407. public function persistEntity(EntityManagerInterface $entityManager, $entityInstance): void
  408. {
  409. $entityManager->create($entityInstance);
  410. $entityManager->flush();
  411. $this->getFlashBagTranslator()->add('success', 'created', $this->getTranslationEntityName());
  412. }
  413. public function deleteEntity(EntityManagerInterface $entityManager, $entityInstance): void
  414. {
  415. if ($this->isInstanceOf(StatusInterface::class)) {
  416. $entityInstance->setStatus(-1);
  417. $entityManager->update($entityInstance);
  418. } else {
  419. $entityManager->delete($entityInstance);
  420. }
  421. $entityManager->flush();
  422. $this->getFlashBagTranslator()->add('success', 'deleted', $this->getTranslationEntityName());
  423. }
  424. public function configureActions(Actions $actions): Actions
  425. {
  426. $this->buildIndexActions($actions);
  427. $this->buildEditActions($actions);
  428. $this->buildDetailActions($actions);
  429. $this->buildNewActions($actions);
  430. $this->handleTranslatableEntityActions($actions);
  431. $this->handleSortableEntityActions($actions);
  432. $this->handleTreeEntityActions($actions);
  433. /*$actions->reorder(Crud::PAGE_EDIT, [ActionDefinition::INDEX, ActionDefinition::SAVE_AND_RETURN, ActionDefinition::SAVE_AND_CONTINUE, ActionDefinition::DELETE]);
  434. $actions->reorder(Crud::PAGE_NEW, [ActionDefinition::INDEX, ActionDefinition::SAVE_AND_RETURN, ActionDefinition::SAVE_AND_ADD_ANOTHER]);*/
  435. return $actions;
  436. }
  437. public function getDuplicateAction(): Action
  438. {
  439. $duplicateAction = Action::new(
  440. ActionDefinition::DUPLICATE,
  441. $this->translatorAdmin->transAction(ActionDefinition::DUPLICATE),
  442. 'fa fa-fw fa-copy'
  443. )
  444. ->linkToCrudAction(ActionDefinition::DUPLICATE)
  445. ->setLabel($this->translatorAdmin->transAction(ActionDefinition::DUPLICATE))
  446. ->setCssClass('in-dropdown text-info action-confirm');
  447. return $duplicateAction;
  448. }
  449. public function buildIndexActions(Actions $actions): void
  450. {
  451. $actions->add(Crud::PAGE_INDEX, $this->getDuplicateAction());
  452. $this->actionUpdate(
  453. $actions,
  454. Crud::PAGE_INDEX,
  455. ActionDefinition::NEW,
  456. [
  457. 'icon' => 'plus',
  458. 'label' => $this->translatorAdmin->transAction('create'),
  459. 'add_class' => 'btn-sm',
  460. ]
  461. );
  462. $this->actionUpdate(
  463. $actions,
  464. Crud::PAGE_INDEX,
  465. ActionDefinition::EDIT,
  466. [
  467. 'class' => 'btn btn-sm btn-primary',
  468. 'icon' => 'edit',
  469. 'label' => false,
  470. 'html_attributes' => array(
  471. 'data-toggle' => 'tooltip',
  472. 'title' => $this->translatorAdmin->transAction('edit'),
  473. ),
  474. ]
  475. );
  476. $this->actionUpdate(
  477. $actions,
  478. Crud::PAGE_INDEX,
  479. ActionDefinition::DETAIL,
  480. [
  481. 'icon' => 'eye',
  482. 'add_class' => 'btn btn-sm btn-success',
  483. 'label' => false,
  484. 'html_attributes' => array(
  485. 'data-toggle' => 'tooltip',
  486. 'title' =>$this->translatorAdmin->transAction('detail'),
  487. ),
  488. ]
  489. );
  490. $this->actionUpdate(
  491. $actions,
  492. Crud::PAGE_INDEX,
  493. ActionDefinition::DELETE,
  494. [
  495. 'icon' => 'trash',
  496. 'dropdown' => true,
  497. 'label' => $this->translatorAdmin->transAction('delete'),
  498. 'class' => 'dropdown-item text-danger in-dropdown action-delete',
  499. ]
  500. );
  501. $this->actionUpdate(
  502. $actions,
  503. Crud::PAGE_INDEX,
  504. ActionDefinition::BATCH_DELETE,
  505. [
  506. 'class' => 'btn btn-sm btn-danger',
  507. 'icon' => 'trash',
  508. 'label' => $this->translatorAdmin->transAction('delete'),
  509. ]
  510. );
  511. }
  512. public function buildEditActions(Actions $actions): void
  513. {
  514. $actions->add(Crud::PAGE_EDIT, ActionDefinition::INDEX);
  515. $actions->add(Crud::PAGE_EDIT, ActionDefinition::DELETE);
  516. $this->actionUpdate(
  517. $actions,
  518. Crud::PAGE_EDIT,
  519. ActionDefinition::SAVE_AND_RETURN,
  520. [
  521. 'add_class' => 'float-right ',
  522. 'icon' => 'check',
  523. 'label' => $this->translatorAdmin->transAction('save_and_return'),
  524. ]
  525. );
  526. $this->actionUpdate(
  527. $actions,
  528. Crud::PAGE_EDIT,
  529. ActionDefinition::INDEX,
  530. [
  531. 'icon' => 'chevron-left',
  532. 'class' => 'btn btn-link',
  533. 'label' => $this->translatorAdmin->transAction('back_index'),
  534. ]
  535. );
  536. $this->actionUpdate(
  537. $actions,
  538. Crud::PAGE_EDIT,
  539. ActionDefinition::SAVE_AND_CONTINUE,
  540. [
  541. 'class' => 'btn btn-info float-right action-save-continue',
  542. 'label' =>$this->translatorAdmin->transAction('save_and_continue'),
  543. ]
  544. );
  545. $this->actionUpdate(
  546. $actions,
  547. Crud::PAGE_EDIT,
  548. ActionDefinition::DELETE,
  549. [
  550. 'icon' => 'trash',
  551. 'class' => 'btn btn-outline-danger action-delete',
  552. 'label' => $this->translatorAdmin->transAction('delete'),
  553. ]
  554. );
  555. }
  556. public function buildDetailActions(Actions $actions): void
  557. {
  558. }
  559. public function buildNewActions(Actions $actions): void
  560. {
  561. $actions->add(Crud::PAGE_NEW, ActionDefinition::INDEX);
  562. $this->actionUpdate(
  563. $actions,
  564. Crud::PAGE_NEW,
  565. ActionDefinition::SAVE_AND_RETURN,
  566. [
  567. 'add_class' => 'float-right',
  568. 'icon' => 'check',
  569. 'label' => $this->translatorAdmin->transAction('save_and_return'),
  570. ]
  571. );
  572. $this->actionUpdate(
  573. $actions,
  574. Crud::PAGE_NEW,
  575. ActionDefinition::INDEX,
  576. [
  577. 'icon' => 'chevron-left',
  578. 'class' => 'btn btn-link',
  579. 'label' => $this->translatorAdmin->transAction('back_index'),
  580. ]
  581. );
  582. $this->actionUpdate(
  583. $actions,
  584. Crud::PAGE_NEW,
  585. ActionDefinition::SAVE_AND_ADD_ANOTHER,
  586. [
  587. 'class' => 'btn btn-info float-right',
  588. 'label' => $this->translatorAdmin->transAction('save_and_add_another'),
  589. ]
  590. );
  591. }
  592. public function handleTranslatableEntityActions(Actions $actions): void
  593. {
  594. if ($this->isInstanceOf(TranslatableInterface::class)) {
  595. $actions->update(
  596. Crud::PAGE_INDEX,
  597. ActionDefinition::EDIT,
  598. function (Action $action) {
  599. $action->setTemplatePath('@LcSov/adminlte/crud/action/translatable.html.twig');
  600. return $action;
  601. }
  602. );
  603. }
  604. }
  605. public function handleSortableEntityActions(Actions $actions): void
  606. {
  607. if ($this->isInstanceOf(SortableInterface::class)) {
  608. $sortAction = Action::new(
  609. ActionDefinition::SORT,
  610. $this->translatorAdmin->transAction(ActionDefinition::SORT),
  611. 'fa fa-sort'
  612. )
  613. ->linkToCrudAction(ActionDefinition::SORT)
  614. ->setCssClass('btn btn-sm btn-success')
  615. ->createAsGlobalAction();
  616. $actions->add(Crud::PAGE_INDEX, $sortAction);
  617. }
  618. }
  619. public function handleTreeEntityActions(Actions $actions): void
  620. {
  621. if ($this->isInstanceOf(TreeInterface::class)) {
  622. $indexChildAction = Action::new(
  623. ActionDefinition::INDEX_CHILDREN,
  624. $this->translatorAdmin->transAction(ActionDefinition::INDEX_CHILDREN),
  625. 'fa fa-list'
  626. )
  627. ->linkToCrudAction(ActionDefinition::INDEX)
  628. ->setLabel('')
  629. ->setHtmlAttributes(array('data-toggle' => 'tooltip', 'title' => 'Afficher les enfants'))
  630. ->setTemplatePath('@LcSov/adminlte/crud/action/index_children.html.twig')
  631. ->setCssClass('btn btn-sm btn-success');
  632. $backParentAction = Action::new(
  633. ActionDefinition::INDEX_PARENT,
  634. $this->getTranslatorAdmin()->transAction(ActionDefinition::INDEX_PARENT),
  635. 'fa fa-chevron-left'
  636. )
  637. ->linkToCrudAction(ActionDefinition::INDEX)
  638. ->setCssClass('btn btn-sm btn-info')
  639. ->createAsGlobalAction();
  640. $actions->add(Crud::PAGE_INDEX, $backParentAction);
  641. $actions->add(Crud::PAGE_INDEX, $indexChildAction);
  642. }
  643. }
  644. public function actionUpdate($actions, $crudActionName, $actionName, array $button): void
  645. {
  646. if ($actions->getAsDto('actions')->getAction($crudActionName, $actionName)) {
  647. $actions->update(
  648. $crudActionName,
  649. $actionName,
  650. function (Action $action) use ($button) {
  651. if (isset($button['add_class'])) {
  652. $action->addCssClass($button['add_class']);
  653. }
  654. if (isset($button['class'])) {
  655. $action->setCssClass($button['class']);
  656. }
  657. if (isset($button['icon'])) {
  658. $action->setIcon('fa fa-' . $button['icon']);
  659. }
  660. if (isset($button['label'])) {
  661. $action->setLabel($button['label']);
  662. }
  663. if (isset($button['dropdown']) && $button['dropdown']) {
  664. $action->addCssClass('in-dropdown');
  665. }
  666. if (isset($button['html_attributes']) && $button['html_attributes']) {
  667. $action->setHtmlAttributes($button['html_attributes']);
  668. }
  669. return $action;
  670. }
  671. );
  672. }
  673. }
  674. public function autocompleteFilter(AdminContext $context): JsonResponse
  675. {
  676. $repositoryQuery = $this->get(EntityRepository::class)->createRepositoryQuery(
  677. $this->getRepositoryQuery(),
  678. $context->getSearch(),
  679. $context->getEntity(),
  680. FieldCollection::new([]),
  681. FilterCollection::new()
  682. );
  683. if ($this->isInstanceOf(StatusInterface::class)) {
  684. $repositoryQuery->filterIsOnlineAndOffline();
  685. }
  686. $autocompleteContext = $context->getRequest()->get(AssociationField::PARAM_AUTOCOMPLETE_CONTEXT);
  687. /** @var CrudControllerInterface $controller */
  688. $controller = $this->get(ControllerFactory::class)->getCrudControllerInstance(
  689. $autocompleteContext[EA::CRUD_CONTROLLER_FQCN],
  690. ActionDefinition::INDEX,
  691. $context->getRequest()
  692. );
  693. /** @var FieldDto $field */
  694. $field = FieldCollection::new(
  695. $controller->configureFields($autocompleteContext['originatingPage'])
  696. )->getByProperty($autocompleteContext['propertyName']);
  697. $filterManager = $this->getFilterManager();
  698. $filteredValue = ['value' => $context->getRequest()->query->get('q')];
  699. $filterManager->applyFilter($repositoryQuery, $field, $filteredValue);
  700. $repositoryQuery->select('.' . $autocompleteContext['propertyName']);
  701. $responses = array();
  702. foreach ($repositoryQuery->find() as $result) {
  703. $responses[] = array_values($result)[0];
  704. }
  705. return JsonResponse::fromJsonString(json_encode($responses));
  706. }
  707. public function createCustomForm($class, $action, $controller, $entity, $dataInOption = true, $options = array())
  708. {
  709. if ($dataInOption) {
  710. $data = $entity;
  711. } else {
  712. $data = null;
  713. }
  714. $options['action'] = $this->get(AdminUrlGenerator::class)
  715. ->setAction($action)
  716. ->setController($controller)
  717. ->setEntityId($entity->getId())
  718. ->generateUrl();
  719. return $this->createForm($class, $data, $options);
  720. }
  721. public function eaBeforeCrudActionEventDelete(AdminContext $context): ?Response
  722. {
  723. $event = new BeforeCrudActionEvent($context);
  724. $this->container->get('event_dispatcher')->dispatch($event);
  725. if ($event->isPropagationStopped()) {
  726. return $event->getResponse();
  727. }
  728. if (!$this->isGranted(Permission::EA_EXECUTE_ACTION, ['action' => Action::DELETE, 'entity' => $context->getEntity()])) {
  729. throw new ForbiddenActionException($context);
  730. }
  731. if (!$context->getEntity()->isAccessible()) {
  732. throw new InsufficientEntityPermissionException($context);
  733. }
  734. $csrfToken = $context->getRequest()->request->get('token');
  735. if (!$this->isCsrfTokenValid('ea-delete', $csrfToken)) {
  736. return $this->redirectToRoute($context->getDashboardRouteName());
  737. }
  738. return null;
  739. }
  740. }