您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

831 行
31KB

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