選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

482 行
18KB

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