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.

781 lines
30KB

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