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.

AbstractAdminController.php 17KB

3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
3 vuotta sitten
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. <?php
  2. namespace Lc\SovBundle\Controller;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Doctrine\ORM\QueryBuilder;
  5. use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
  6. use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
  7. use EasyCorp\Bundle\EasyAdminBundle\Config\Action;
  8. use EasyCorp\Bundle\EasyAdminBundle\Config\Actions;
  9. use EasyCorp\Bundle\EasyAdminBundle\Config\Assets;
  10. use EasyCorp\Bundle\EasyAdminBundle\Config\Crud;
  11. use EasyCorp\Bundle\EasyAdminBundle\Config\KeyValueStore;
  12. use EasyCorp\Bundle\EasyAdminBundle\Config\Option\EA;
  13. use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
  14. use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController as EaAbstractCrudController;
  15. use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
  16. use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
  17. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterCrudActionEvent;
  18. use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
  19. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeCrudActionEvent;
  20. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityDeletedEvent;
  21. use EasyCorp\Bundle\EasyAdminBundle\Event\BeforeEntityUpdatedEvent;
  22. use EasyCorp\Bundle\EasyAdminBundle\Exception\ForbiddenActionException;
  23. use EasyCorp\Bundle\EasyAdminBundle\Exception\InsufficientEntityPermissionException;
  24. use EasyCorp\Bundle\EasyAdminBundle\Factory\EntityFactory;
  25. use EasyCorp\Bundle\EasyAdminBundle\Factory\FilterFactory;
  26. use EasyCorp\Bundle\EasyAdminBundle\Factory\PaginatorFactory;
  27. use EasyCorp\Bundle\EasyAdminBundle\Field\FormField;
  28. use EasyCorp\Bundle\EasyAdminBundle\Field\TextareaField;
  29. use EasyCorp\Bundle\EasyAdminBundle\Field\TextField;
  30. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  31. use EasyCorp\Bundle\EasyAdminBundle\Security\Permission;
  32. use Lc\SovBundle\Doctrine\EntityManager;
  33. use Lc\SovBundle\Doctrine\Extension\DevAliasInterface;
  34. use Lc\SovBundle\Doctrine\Extension\SeoInterface;
  35. use Lc\SovBundle\Doctrine\Extension\SortableInterface;
  36. use Lc\SovBundle\Doctrine\Extension\TranslatableInterface;
  37. use Lc\SovBundle\Doctrine\Extension\TreeInterface;
  38. use Lc\SovBundle\Field\CollectionField;
  39. use Lc\SovBundle\Field\GalleryManagerField;
  40. use Lc\SovBundle\Form\Type\Crud\PositionType;
  41. use Lc\SovBundle\Translation\TranslatorAdmin;
  42. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  43. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  44. use Symfony\Component\Form\Extension\Core\Type\TextType;
  45. use Symfony\Component\HttpFoundation\RequestStack;
  46. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  47. abstract class AbstractAdminController extends EaAbstractCrudController
  48. {
  49. protected $session;
  50. protected $request;
  51. protected $em;
  52. protected $translatorAdmin;
  53. public function __construct(
  54. SessionInterface $session,
  55. RequestStack $request,
  56. EntityManagerInterface $em,
  57. TranslatorAdmin $translatorAdmin
  58. )
  59. {
  60. $this->session = $session;
  61. $this->request = $request;
  62. $this->em = $em;
  63. $this->translatorAdmin = $translatorAdmin;
  64. }
  65. public function configureActions(Actions $actions): Actions
  66. {
  67. /* Translatable */
  68. if ($this->isInstanceOf(TranslatableInterface::class)) {
  69. $actions->update(
  70. Crud::PAGE_INDEX,
  71. Action::EDIT,
  72. function (Action $action) {
  73. $action->setTemplatePath('@LcSov/adminlte/crud/action/translatable.html.twig');
  74. return $action;
  75. }
  76. );
  77. }
  78. /* Boutons des actions dans les listes */
  79. $actionsArray[Crud::PAGE_INDEX] = [
  80. Action::NEW => [
  81. 'icon' => 'plus',
  82. 'label' => $this->translatorAdmin->transAction('create'),
  83. 'add_class' => 'btn-sm'
  84. ],
  85. Action::EDIT => [
  86. 'class' => 'btn btn-sm btn-primary',
  87. 'icon' => 'edit',
  88. 'label' => false,
  89. 'html_attributes' => array(
  90. 'data-toggle' => 'tooltip',
  91. 'title' => $this->translatorAdmin->transAction('edit')
  92. )
  93. ],
  94. Action::DELETE => [
  95. 'icon' => 'trash',
  96. 'dropdown' => true,
  97. 'label' => $this->translatorAdmin->transAction('delete')
  98. ],
  99. Action::BATCH_DELETE => [
  100. 'class' => 'btn btn-sm btn-danger',
  101. 'icon' => 'trash',
  102. 'label' => $this->translatorAdmin->transAction('delete')
  103. ],
  104. ];
  105. /* Boutons des actions dans l'édition */
  106. $actionSaveAndReturn = [
  107. 'add_class' => 'float-right',
  108. 'icon' => 'check',
  109. 'label' => $this->translatorAdmin->transAction('save_and_return')
  110. ];
  111. $actionIndex = [
  112. 'icon' => 'chevron-left',
  113. 'class' => 'btn btn-link',
  114. 'label' => $this->translatorAdmin->transAction('back_index')
  115. ];
  116. $actionsArray[Crud::PAGE_EDIT] = [
  117. Action::SAVE_AND_CONTINUE => [
  118. 'class' => 'btn btn-info float-right',
  119. 'label' => $this->translatorAdmin->transAction('save_and_continue')
  120. ],
  121. Action::DELETE => [
  122. 'icon' => 'trash',
  123. 'class' => 'btn btn-outline-danger action-delete',
  124. 'label' => $this->translatorAdmin->transAction('delete')
  125. ],
  126. Action::SAVE_AND_RETURN => $actionSaveAndReturn,
  127. Action::INDEX => $actionIndex,
  128. ];
  129. $actionsArray[Crud::PAGE_NEW] = [
  130. Action::SAVE_AND_ADD_ANOTHER => [
  131. 'class' => 'btn btn-info float-right',
  132. 'label' => $this->translatorAdmin->transAction('save_and_add_another')
  133. ],
  134. Action::SAVE_AND_RETURN => $actionSaveAndReturn,
  135. Action::INDEX => $actionIndex,
  136. ];
  137. $actions->add(Crud::PAGE_EDIT, Action::INDEX);
  138. $actions->add(Crud::PAGE_EDIT, Action::DELETE);
  139. $actions->add(Crud::PAGE_NEW, Action::INDEX);
  140. if ($this->isInstanceOf(SortableInterface::class)) {
  141. $sortAction = Action::new('sort', $this->translatorAdmin->transAction('sort'), 'fa fa-sort')
  142. ->linkToCrudAction('sort')
  143. ->setCssClass('btn btn-sm btn-success')
  144. ->createAsGlobalAction();
  145. $actions->add(Crud::PAGE_INDEX, $sortAction);
  146. }
  147. if ($this->isInstanceOf(TreeInterface::class)) {
  148. $indexChildAction = Action::new(
  149. 'index_children',
  150. $this->translatorAdmin->transAction('index_children'),
  151. 'fa fa-list'
  152. )
  153. ->linkToCrudAction(Action::INDEX)
  154. ->setLabel('')
  155. ->setHtmlAttributes(array('data-toggle' => 'tooltip', 'title' => 'Afficher les enfants'))
  156. ->setTemplatePath('@LcSov/adminlte/crud/action/index_children.html.twig')
  157. ->setCssClass('btn btn-sm btn-success');
  158. $backParentAction = Action::new(
  159. 'index_parent',
  160. $this->translatorAdmin->transAction('index_parent'),
  161. 'fa fa-chevron-left'
  162. )
  163. ->linkToCrudAction(Action::INDEX)
  164. ->setCssClass('btn btn-sm btn-info')
  165. ->createAsGlobalAction();
  166. $actions->add(Crud::PAGE_INDEX, $backParentAction);
  167. $actions->add(Crud::PAGE_INDEX, $indexChildAction);
  168. }
  169. $actions->reorder(Crud::PAGE_EDIT, [Action::INDEX, Action::SAVE_AND_RETURN, Action::SAVE_AND_CONTINUE]);
  170. $actions->reorder(Crud::PAGE_NEW, [Action::INDEX, Action::SAVE_AND_RETURN, Action::SAVE_AND_ADD_ANOTHER]);
  171. foreach ($actionsArray as $crudActionName => $actionsStyle) {
  172. foreach ($actionsStyle as $actionName => $button) {
  173. $actions->update(
  174. $crudActionName,
  175. $actionName,
  176. function (Action $action) use ($button) {
  177. if (isset($button['add_class'])) {
  178. $action->addCssClass($button['add_class']);
  179. }
  180. if (isset($button['class'])) {
  181. $action->setCssClass($button['class']);
  182. }
  183. if (isset($button['icon'])) {
  184. $action->setIcon('fa fa-' . $button['icon']);
  185. }
  186. if (isset($button['label'])) {
  187. $action->setLabel($button['label']);
  188. }
  189. if (isset($button['dropdown']) && $button['dropdown']) {
  190. $action->addCssClass('in-dropdown');
  191. }
  192. if (isset($button['html_attributes']) && $button['html_attributes']) {
  193. $action->setHtmlAttributes($button['html_attributes']);
  194. }
  195. return $action;
  196. }
  197. );
  198. }
  199. }
  200. return $actions;
  201. }
  202. public function configureResponseParameters(KeyValueStore $responseParameters): KeyValueStore
  203. {
  204. if (Crud::PAGE_INDEX === $responseParameters->get('pageName')) {
  205. $responseParameters->set('fields', $this->configureFields('index'));
  206. }
  207. return $responseParameters;
  208. }
  209. public function configureCrud(Crud $crud): Crud
  210. {
  211. $crud = parent::configureCrud($crud);
  212. $this->setMaxResults($crud);
  213. if ($this->isInstanceOf(SortableInterface::class)) {
  214. $crud->setDefaultSort(['position' => 'ASC']);
  215. }
  216. return $crud;
  217. }
  218. public function setMaxResults(Crud $crud)
  219. {
  220. $entityClass = $this->getEntityFqcn();
  221. $paramListMaxResults = 'listMaxResults';
  222. $paramSessionListMaxResults = $entityClass . '-' . $paramListMaxResults;
  223. $requestListMaxResults = $this->request->getCurrentRequest()->get($paramListMaxResults);
  224. if ($requestListMaxResults) {
  225. $this->session->set($paramSessionListMaxResults, $requestListMaxResults);
  226. }
  227. $maxResults = $this->session->get($paramSessionListMaxResults) ? $this->session->get(
  228. $paramSessionListMaxResults
  229. ) : 30;
  230. $crud->setPaginatorPageSize($maxResults);
  231. }
  232. public function configureFields(string $pageName): iterable
  233. {
  234. $seoPanel = $confPanel = array();
  235. if ($this->isInstanceOf(SeoInterface::class)) {
  236. $seoPanel = [
  237. FormField::addPanel('seo')->setTemplateName('crud/field/generic'),
  238. TextField::new('metaTitle')->setLabel('Meta Title')->setHelp(
  239. 'Affiché dans les résultats de recherche Google'
  240. )->hideOnIndex(),
  241. TextareaField::new('metaDescription')->setLabel('Meta description')->setHelp(
  242. 'Affiché dans les résultats de recherche Google'
  243. )->hideOnIndex(),
  244. CollectionField::new('oldUrls')
  245. ->setFormTypeOption('entry_type', TextType::class)->setLabel(
  246. 'Anciennes urls du document'
  247. )->hideOnIndex(),
  248. ];
  249. }
  250. if ($this->isInstanceOf(DevAliasInterface::class)) {
  251. $confPanel = [
  252. FormField::addPanel('configuration')->setTemplateName('crud/field/generic'),
  253. TextField::new('devAlias')->hideOnIndex(),
  254. ];
  255. }
  256. return array_merge($seoPanel, $confPanel);
  257. }
  258. public function sort(AdminContext $context)
  259. {
  260. $event = new BeforeCrudActionEvent($context);
  261. $this->get('event_dispatcher')->dispatch($event);
  262. if ($event->isPropagationStopped()) {
  263. return $event->getResponse();
  264. }
  265. if (!$this->isGranted(Permission::EA_EXECUTE_ACTION) || !$this->isInstanceOf(SortableInterface::class)) {
  266. throw new ForbiddenActionException($context);
  267. }
  268. $fields = FieldCollection::new($this->configureFields(Crud::PAGE_INDEX));
  269. $filters = $this->get(FilterFactory::class)->create(
  270. $context->getCrud()->getFiltersConfig(),
  271. $fields,
  272. $context->getEntity()
  273. );
  274. $queryBuilder = $this->createIndexQueryBuilder($context->getSearch(), $context->getEntity(), $fields, $filters);
  275. $paginator = $this->get(PaginatorFactory::class)->create($queryBuilder);
  276. $entities = $this->get(EntityFactory::class)->createCollection($context->getEntity(), $paginator->getResults());
  277. $this->get(EntityFactory::class)->processFieldsForAll($entities, $fields);
  278. $sortableForm = $this->createFormBuilder(array('entities', $paginator->getResults()))
  279. ->add(
  280. 'entities',
  281. CollectionType::class,
  282. array(
  283. 'required' => true,
  284. 'allow_add' => true,
  285. 'entry_type' => PositionType::class,
  286. )
  287. )
  288. ->getForm();
  289. $entityManager = $this->getDoctrine()->getManagerForClass($this->getEntityFqcn());
  290. $repository = $entityManager->getRepository($this->getEntityFqcn());
  291. $sortableForm->handleRequest($context->getRequest());
  292. if ($sortableForm->isSubmitted() && $sortableForm->isValid()) {
  293. foreach ($sortableForm->get('entities')->getData() as $elm) {
  294. $entityInstance = $repository->find($elm['id']);
  295. $entityDto = $context->getEntity()->newWithInstance($entityInstance);
  296. if (!$entityDto->isAccessible()) {
  297. throw new InsufficientEntityPermissionException($context);
  298. }
  299. $event = new BeforeEntityDeletedEvent($entityInstance);
  300. $this->get('event_dispatcher')->dispatch($event);
  301. $entityInstance = $event->getEntityInstance();
  302. $entityInstance->setPosition($elm['position']);
  303. $this->updateEntity($entityManager, $entityInstance);
  304. $this->get('event_dispatcher')->dispatch(new AfterEntityUpdatedEvent($entityInstance));
  305. }
  306. $url = $this->get(AdminUrlGenerator::class)
  307. ->setAction(Action::INDEX)
  308. ->generateUrl();
  309. $this->addFlash('success', $this->translatorAdmin->transFlashMessage('sort'), array());
  310. return $this->redirect($url);
  311. }
  312. $responseParameters = $this->configureResponseParameters(
  313. KeyValueStore::new(
  314. [
  315. 'pageName' => Crud::PAGE_INDEX,
  316. 'templatePath' => '@LcSov/adminlte/crud/sort.html.twig',
  317. 'entities' => $entities,
  318. 'paginator' => $paginator,
  319. 'global_actions' => array(),
  320. 'batch_actions' => array(),
  321. 'filters' => $filters,
  322. 'sortable_form' => $sortableForm,
  323. ]
  324. )
  325. );
  326. $responseParameters->set('fields', $this->configureFields('index'));
  327. $event = new AfterCrudActionEvent($context, $responseParameters);
  328. $this->get('event_dispatcher')->dispatch($event);
  329. if ($event->isPropagationStopped()) {
  330. return $event->getResponse();
  331. }
  332. return $responseParameters;
  333. }
  334. public function createIndexQueryBuilder(
  335. SearchDto $searchDto,
  336. EntityDto $entityDto,
  337. FieldCollection $fields,
  338. FilterCollection $filters
  339. ): QueryBuilder {
  340. $queryBuilder = parent::createIndexQueryBuilder(
  341. $searchDto,
  342. $entityDto,
  343. $fields,
  344. $filters
  345. );
  346. if ($this->isInstanceOf(TreeInterface::class)) {
  347. $entityId = $searchDto->getRequest()->get('entityId');
  348. if ($entityId !== null) {
  349. $queryBuilder->andWhere('entity.parent = :entityId');
  350. $queryBuilder->setParameter('entityId', $searchDto->getRequest()->get('entityId'));
  351. } else {
  352. $queryBuilder->andWhere('entity.parent IS NULL');
  353. }
  354. }
  355. return $queryBuilder;
  356. }
  357. public function createSortQueryBuilder(
  358. SearchDto $searchDto,
  359. EntityDto $entityDto,
  360. FieldCollection $fields,
  361. FilterCollection $filters
  362. ): QueryBuilder {
  363. $queryBuilder = $this->createIndexQueryBuilder($searchDto,$entityDto,$fields,$filters);
  364. return $queryBuilder;
  365. }
  366. public function edit(AdminContext $context)
  367. {
  368. $response = parent::edit($context);;
  369. // on vide le flash bag si édition en ajax (notification déjà affichée en Javascript)
  370. if ($context->getRequest()->isXmlHttpRequest()) {
  371. $this->session->getFlashBag()->clear();
  372. }
  373. return $response;
  374. }
  375. public function isInstanceOf(string $interfaceName): bool
  376. {
  377. return in_array($interfaceName, class_implements($this->getEntityFqcn()));
  378. }
  379. public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
  380. {
  381. $entityManager->update($entityInstance);
  382. $entityManager->flush();
  383. }
  384. public function persistEntity(EntityManagerInterface $entityManager, $entityInstance): void
  385. {
  386. dump($entityInstance);
  387. die();
  388. $entityManager->create($entityInstance);
  389. $entityManager->flush();
  390. }
  391. }