Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

701 lines
35KB

  1. <?php
  2. namespace Lc\ShopBundle\Controller\Backend;
  3. use Doctrine\ORM\EntityManagerInterface;
  4. use Doctrine\ORM\EntityRepository;
  5. use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;
  6. use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
  7. use FOS\UserBundle\Model\UserManagerInterface;
  8. use Lc\ShopBundle\Context\FilterMultipleMerchantsInterface;
  9. use Lc\ShopBundle\Context\ImageInterface;
  10. use Lc\ShopBundle\Context\MerchantInterface;
  11. use Lc\ShopBundle\Context\ReminderInterface;
  12. use Lc\ShopBundle\Context\SeoInterface;
  13. use Lc\ShopBundle\Context\StatusInterface;
  14. use Lc\ShopBundle\Context\TreeInterface;
  15. use Lc\ShopBundle\Form\Backend\Common\AbstractEditPositionType;
  16. use Lc\ShopBundle\Form\Backend\Filters\ListFilterType;
  17. use Lc\ShopBundle\Model\User;
  18. use Lc\ShopBundle\Services\UtilsManager;
  19. use Mailjet\MailjetSwiftMailer\SwiftMailer\MailjetTransport;
  20. use Symfony\Bridge\Doctrine\Form\Type\EntityType;
  21. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  22. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  23. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  24. use Symfony\Component\Form\Extension\Core\Type\TextareaType;
  25. use Symfony\Component\Form\Extension\Core\Type\TextType;
  26. use Symfony\Component\Form\FormEvent;
  27. use Symfony\Component\Form\FormEvents;
  28. use Symfony\Component\HttpFoundation\JsonResponse;
  29. use Symfony\Component\HttpFoundation\Response;
  30. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  31. use Symfony\Component\Security\Core\Security;
  32. use Symfony\Contracts\Translation\TranslatorInterface;
  33. class AdminController extends EasyAdminController
  34. {
  35. protected $security;
  36. protected $userManager;
  37. protected $em;
  38. protected $utils;
  39. protected $merchantUtils;
  40. protected $mailjetTransport;
  41. protected $orderUtils;
  42. protected $mailUtils;
  43. protected $translator;
  44. protected $utilsProcess;
  45. protected $session;
  46. protected $sectionUtils;
  47. protected $filtersForm = null;
  48. public function __construct(Security $security, UserManagerInterface $userManager, EntityManagerInterface $em,
  49. MailjetTransport $mailjetTransport, UtilsManager $utilsManager, TranslatorInterface $translator, SessionInterface $session)
  50. {
  51. $this->security = $security;
  52. $this->userManager = $userManager;
  53. $this->em = $em;
  54. $this->mailjetTransport = $mailjetTransport;
  55. $this->utils = $utilsManager->getUtils();
  56. $this->merchantUtils = $utilsManager->getMerchantUtils();
  57. $this->orderUtils = $utilsManager->getOrderUtils();;
  58. $this->mailUtils = $utilsManager->getMailUtils();
  59. $this->utilsProcess = $utilsManager->getUtilsProcess();
  60. $this->sectionUtils = $utilsManager->getSectionUtils();
  61. $this->translator = $translator;
  62. $this->session = $session;
  63. }
  64. public function createCustomForm($class, $action, $parameters, $data = true, $options = array())
  65. {
  66. if ($data) $options['data'] = $parameters['entity'];
  67. $options['action'] = $this->generateUrl('easyadmin', array(
  68. 'action' => $action,
  69. 'entity' => $this->entity['name'],
  70. 'id' => $parameters['entity']->getId()
  71. ));
  72. return $this->createForm($class, null, $options);
  73. }
  74. public function autocompleteAction()
  75. {
  76. $entityName = $this->request->query->get('entity');
  77. $valueSearched = $this->request->query->get('q');
  78. $field = $this->request->query->get('field');
  79. $class = $this->entity['class'];
  80. $repo = $this->em->getRepository($class);
  81. $values = $repo->findByTerm($field, $valueSearched);
  82. $response = array();
  83. foreach ($values as $value) {
  84. $response[] = $value[$field];
  85. }
  86. return new JsonResponse($response);
  87. }
  88. /**
  89. * Réécriture de show action pr rediriger vers l'édition
  90. */
  91. public function showAction()
  92. {
  93. $id = $this->request->query->get('id');
  94. $entity = $this->request->query->get('entity');
  95. return $this->redirectToRoute('easyadmin', [
  96. 'action' => 'edit',
  97. 'entity' => $entity,
  98. 'id' => $id
  99. ]);
  100. }
  101. /**
  102. * Réécriture de removeEntity pour passer les status à -1
  103. */
  104. protected function removeEntity($entity)
  105. {
  106. if ($entity instanceof StatusInterface) {
  107. $entity->setStatus(-1);
  108. $this->em->persist($entity);
  109. $this->em->flush();
  110. } else {
  111. parent::removeEntity($entity);
  112. }
  113. }
  114. protected function commonDqlFilterQueryBuilder($entityClass, $dqlFilter)
  115. {
  116. if ($pos = strpos($dqlFilter, 'currentMerchant')) {
  117. $dqlFilter = sprintf(str_replace('currentMerchant', $this->getUser()->getMerchant()->getId(), $dqlFilter));
  118. }
  119. if ($pos = strpos($dqlFilter, 'NOW()')) {
  120. $date = new \DateTime();
  121. $dqlFilter = sprintf(str_replace('NOW()', $date->format('Y-m-d H:i:s'), $dqlFilter));
  122. }
  123. if ($pos = strpos($dqlFilter, 'sectionLunch')) {
  124. $dqlFilter = sprintf(str_replace('sectionLunch', $this->sectionUtils->getSection('lunch')->getId(), $dqlFilter));
  125. } else if ($pos = strpos($dqlFilter, 'sectionMarket')) {
  126. $dqlFilter = sprintf(str_replace('sectionMarket', $this->sectionUtils->getSection('market')->getId(), $dqlFilter));
  127. }
  128. if (new $entityClass instanceof StatusInterface && strpos($dqlFilter, 'entity.status') === false) {
  129. if ($dqlFilter) $dqlFilter .= sprintf(' AND entity.status > = 0');
  130. else $dqlFilter .= sprintf(' entity.status > = 0');
  131. }
  132. return $dqlFilter;
  133. }
  134. protected function commonQueryFilter($entityClass, $queryBuilder)
  135. {
  136. if (new $entityClass instanceof FilterMultipleMerchantsInterface) {
  137. $queryBuilder->andWhere(':currentMerchant MEMBER OF entity.merchants')
  138. ->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  139. }
  140. }
  141. protected function createSearchQueryBuilder($entityClass, $searchQuery, array $searchableFields, $sortField = null, $sortDirection = null, $dqlFilter = null)
  142. {
  143. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter);
  144. $queryBuilder = parent::createSearchQueryBuilder($entityClass, $searchQuery, $searchableFields, $sortField, $sortDirection, $dqlFilter);
  145. $this->commonQueryFilter($entityClass, $queryBuilder);
  146. return $queryBuilder;
  147. }
  148. protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
  149. {
  150. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter);
  151. $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
  152. $this->commonQueryFilter($entityClass, $queryBuilder);
  153. $listFields = $this->entity['list']['fields'];
  154. $this->filtersForm = $this->createForm(ListFilterType::class, null, array(
  155. 'fields' => $listFields,
  156. 'method' => 'get',
  157. 'entity_name' => $this->entity['name'],
  158. //'entityClass' => $this->entity['class'],
  159. 'entity_class' => $this->entity['class']
  160. ));
  161. $this->filtersForm->handleRequest($this->request);
  162. if ($this->filtersForm->isSubmitted() && $this->filtersForm->isValid()) {
  163. foreach ($listFields as $field) {
  164. if ($this->filtersForm->has($field['property'])) {
  165. switch ($field['dataType']) {
  166. case 'option':
  167. case 'integer':
  168. case 'text':
  169. case 'string':
  170. case 'toggle':
  171. $filter = $this->filtersForm->get($field['property'])->getData();
  172. if ($filter !== null) {
  173. $queryBuilder->andWhere('entity.' . $field['property'] . ' LIKE :' . $field['property'] . '');
  174. $queryBuilder->setParameter($field['property'], '%' . $filter . '%');
  175. }
  176. break;
  177. case 'association' :
  178. $filter = $this->filtersForm->get($field['property'])->getData();
  179. if ($filter !== null) {
  180. if ($field['type_options']['multiple']) {
  181. $queryBuilder->andWhere(':' . $field['property'] . ' MEMBER OF entity.' . $field['property'] . '');
  182. } else {
  183. $queryBuilder->andWhere('entity.' . $field['property'] . ' = :' . $field['property'] . '');
  184. }
  185. if ($filter instanceof TreeInterface && $filter->getParent() == null) {
  186. $queryBuilder->setParameter($field['property'], array_merge(array($filter), $filter->getChildrens()->toArray()));
  187. } else {
  188. $queryBuilder->setParameter($field['property'], $filter);
  189. }
  190. }
  191. break;
  192. case 'datetime':
  193. case 'date':
  194. $dateStart = $this->filtersForm->get($field['property'])->get('dateStart')->getData();
  195. $dateEnd = $this->filtersForm->get($field['property'])->get('dateEnd')->getData();
  196. if ($dateStart) $queryBuilder->andWhere('entity.' . $field['property'] . ' >= :dateStart')->setParameter('dateStart', $dateStart);
  197. if ($dateEnd) $queryBuilder->andWhere('entity.' . $field['property'] . ' <= :dateEnd')->setParameter('dateEnd', $dateEnd);
  198. }
  199. }
  200. }
  201. }
  202. return $queryBuilder;
  203. }
  204. public function renderTemplate($actionName, $templatePath, array $parameters = [])
  205. {
  206. $reminderRepo = $this->em->getRepository(ReminderInterface::class);
  207. $easyadmin = $this->request->attributes->get('easyadmin');
  208. $entityName = $easyadmin['entity']['name'];
  209. $id = null;
  210. if ($easyadmin['item']) $id = $easyadmin['item']->getId();
  211. $user = $this->security->getUser();
  212. $reminders = array('reminders' => $reminderRepo->findByEasyAdminConfigAndUser($actionName, $entityName, $user, $id));
  213. if ($actionName == 'list') {
  214. if ($this->filtersForm === null) {
  215. $options['fields'] = $parameters['fields'];
  216. $options['method'] = 'get';
  217. $this->filtersForm = $this->createForm(ListFilterType::class, null, $options);
  218. }
  219. $parameters = array_merge(
  220. $parameters,
  221. array(
  222. 'filters_form' => $this->filtersForm->createView()
  223. )
  224. );
  225. }
  226. $parameters = array_merge(
  227. $parameters,
  228. $this->getTwigExtraParameters(),
  229. $reminders
  230. );
  231. return parent::renderTemplate($actionName, $templatePath, $parameters);
  232. }
  233. public function getTwigExtraParameters()
  234. {
  235. $repositoryMerchant = $this->getDoctrine()->getRepository(MerchantInterface::class);
  236. $merchants = $repositoryMerchant->findAll();
  237. $user = $this->security->getUser();
  238. return [
  239. 'merchants' => $merchants,
  240. 'current_merchant' => ($user && $user->getMerchant()) ? $user->getMerchant() : null,
  241. ];
  242. }
  243. public function listChildrenAction()
  244. {
  245. $this->dispatch(EasyAdminEvents::PRE_LIST);
  246. $id = $this->request->query->get('id');
  247. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  248. $easyadmin = $this->request->attributes->get('easyadmin');
  249. $entity = $easyadmin['item'];
  250. $fields = $this->entity['list']['fields'];
  251. $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), $this->entity['list']['max_results'], $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);
  252. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  253. $parameters = [
  254. 'paginator' => $paginator,
  255. 'fields' => $fields,
  256. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  257. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  258. 'entity' => $entity,
  259. ];
  260. return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
  261. }
  262. protected function getListParam($param, $default =null){
  263. $entityName = $this->entity['name'];
  264. $sessionParam = $entityName.$param;
  265. //CUSTOM
  266. if($param == 'maxResults'){
  267. $val = $this->entity['list']['max_results'];
  268. }else{
  269. $val = $this->request->query->get($param, $default);
  270. }
  271. if(isset($_GET[$param])){
  272. $val = $this->request->query->get($param);
  273. $this->session->set($sessionParam, $val);
  274. }else if($this->session->get($sessionParam)){
  275. $val = $this->session->get($sessionParam);
  276. $this->request->query->set($param, $val);
  277. }
  278. return $val;
  279. }
  280. protected function listAction()
  281. {
  282. $this->dispatch(EasyAdminEvents::PRE_LIST);
  283. $fields = $this->entity['list']['fields'];
  284. $paginator = $this->findAll($this->entity['class'], $this->getListParam('page', 1), $this->getListParam('maxResults'), $this->getListParam('sortField'), $this->getListParam('sortDirection'), $this->entity['list']['dql_filter']);
  285. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  286. $parameters = [
  287. 'paginator' => $paginator,
  288. 'fields' => $fields,
  289. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  290. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  291. ];
  292. return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
  293. }
  294. public function sortAction()
  295. {
  296. $this->dispatch(EasyAdminEvents::PRE_LIST);
  297. $entity = null;
  298. //Replace this with query builder function, do not use finAll of easyAdmin
  299. if ($this->request->query->get('id')) {
  300. $id = $this->request->query->get('id');
  301. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  302. $easyadmin = $this->request->attributes->get('easyadmin');
  303. $entity = $easyadmin['item'];
  304. }
  305. if ($this->entity['list']['dql_filter']) $this->entity['list']['dql_filter'] .= sprintf(' AND entity.status = 1');
  306. else $this->entity['list']['dql_filter'] .= sprintf(' entity.status = 1');
  307. $fields = $this->entity['list']['fields'];
  308. $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), 500, $this->request->query->get('sortField'), $this->request->query->get('sortDirection'), $this->entity['list']['dql_filter']);
  309. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  310. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  311. ->add('entities', CollectionType::class, array(
  312. 'required' => true,
  313. 'allow_add' => true,
  314. 'entry_type' => AbstractEditPositionType::class,
  315. ))
  316. ->getForm();
  317. $positionForm->handleRequest($this->request);
  318. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  319. $class = $this->entity['class'];
  320. $repo = $this->em->getRepository($class);
  321. $latsPos = 0;
  322. foreach ($positionForm->get('entities')->getData() as $elm) {
  323. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  324. $entity = $repo->find($elm['id']);
  325. $entity->setPosition($elm['position']);
  326. $this->em->persist($entity);
  327. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  328. $latsPos = $elm['position'];
  329. }
  330. //die();
  331. //die();
  332. //to do récupérer les élements hors ligne et incrémenter position
  333. /*foreach ($repo->findBy(array('status'=> false)) as $offlineEntity) {
  334. $latsPos++;
  335. $offlineEntity->setPosition($latsPos);
  336. $this->em->persist($offlineEntity);
  337. }*/
  338. $this->em->flush();
  339. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  340. return $this->redirectToReferrer();
  341. }
  342. $parameters = [
  343. 'paginator' => $paginator,
  344. 'fields' => $fields,
  345. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  346. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  347. 'postion_form' => $positionForm->createView(),
  348. 'entity' => $entity,
  349. 'sortable' => true
  350. ];
  351. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  352. }
  353. public function createEntityFormBuilder($entity, $view, $override = true)
  354. {
  355. $formBuilder = parent::createEntityFormBuilder($entity, $view);
  356. if ($override) $formBuilder = $this->overrideFormBuilder($formBuilder, $entity, $view);
  357. return $formBuilder;
  358. }
  359. public function overrideFormBuilder($formBuilder, $entity, $view)
  360. {
  361. $id = (null !== $entity->getId()) ? $entity->getId() : 0;
  362. if ($entity instanceof SeoInterface) {
  363. $formBuilder->add('metaTitle', TextType::class, array(
  364. 'required' => false,
  365. 'translation_domain' => 'lcshop'
  366. )
  367. );
  368. $formBuilder->add('metaDescription', TextareaType::class, array(
  369. 'required' => false,
  370. 'translation_domain' => 'lcshop'
  371. )
  372. );
  373. /*$formBuilder->add('oldUrls', TextareaType::class, array(
  374. 'required' => false,
  375. 'translation_domain' => 'lcshop'
  376. )
  377. );*/
  378. }
  379. if ($entity instanceof StatusInterface) {
  380. $formBuilder->add('status', ChoiceType::class, array(
  381. 'choices' => array(
  382. 'field.default.statusOptions.offline' => '0',
  383. 'field.default.statusOptions.online' => '1'
  384. ),
  385. 'expanded' => true,
  386. 'required' => true,
  387. 'translation_domain' => 'lcshop'
  388. )
  389. );
  390. }
  391. if ($entity instanceof TreeInterface) {
  392. $formBuilder->add('parent', EntityType::class, array(
  393. 'class' => $this->entity['class'],
  394. 'query_builder' => function (EntityRepository $repo) use ($id) {
  395. return $repo->createQueryBuilder('e')
  396. ->where('e.parent is NULL')
  397. ->andWhere('e.status >= 0')
  398. ->orderBy('e.status', "DESC");
  399. },
  400. 'required' => false,
  401. )
  402. );
  403. }
  404. $formBuilder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
  405. $form = $event->getForm();
  406. $childrens = $form->all();
  407. $this->loopFormField($form, $childrens);
  408. });
  409. return $formBuilder;
  410. }
  411. private function loopFormField($form, $childrens)
  412. {
  413. foreach ($childrens as $child) {
  414. $statusInterface = false;
  415. $treeInterface = false;
  416. $type = $child->getConfig()->getType()->getInnerType();;
  417. if ($type instanceof EntityType) {
  418. $passedOptions = $child->getConfig()->getOptions();
  419. $classImplements = class_implements($passedOptions['class']);
  420. $isFilterMerchantInterface = in_array('Lc\ShopBundle\Context\FilterMerchantInterface', $classImplements);
  421. $isFilterMultipleMerchantsInterface = in_array('Lc\ShopBundle\Context\FilterMultipleMerchantsInterface', $classImplements);
  422. if ($isFilterMerchantInterface || $isFilterMultipleMerchantsInterface) {
  423. if (in_array('Lc\ShopBundle\Context\StatusInterface', $classImplements)) {
  424. $statusInterface = true;
  425. }
  426. if (in_array('Lc\ShopBundle\Context\TreeInterface', $classImplements)) {
  427. $treeInterface = true;
  428. }
  429. $propertyMerchant = 'merchant';
  430. if ($isFilterMultipleMerchantsInterface) {
  431. $propertyMerchant .= 's';
  432. }
  433. $form->add($child->getName(), EntityType::class, array(
  434. 'class' => $this->em->getClassMetadata($passedOptions['class'])->getName(),
  435. 'label' => $passedOptions['label'],
  436. 'expanded' => isset($passedOptions['expanded']) ? $passedOptions['expanded'] : false,
  437. 'multiple' => isset($passedOptions['multiple']) ? $passedOptions['multiple'] : false,
  438. 'placeholder' => '--',
  439. 'translation_domain' => 'lcshop',
  440. 'query_builder' => function (EntityRepository $repo) use ($passedOptions, $propertyMerchant, $statusInterface, $treeInterface, $child) {
  441. $queryBuilder = $repo->createQueryBuilder('e');
  442. $propertyMerchant = 'e.' . $propertyMerchant;
  443. if ($passedOptions['class'] == 'App\Entity\PointSale') {
  444. $queryBuilder->where(':currentMerchant MEMBER OF ' . $propertyMerchant);
  445. } else {
  446. $queryBuilder->where($propertyMerchant . ' = :currentMerchant');
  447. }
  448. if ($statusInterface) {
  449. $queryBuilder->andWhere('e.status >= 0');
  450. }
  451. if ($treeInterface && $child->getName() == 'parent') {
  452. $queryBuilder->andWhere('e.parent is null');
  453. }
  454. $queryBuilder->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  455. return $queryBuilder;
  456. },
  457. 'choice_label' => function ($choice) {
  458. if ($choice instanceof StatusInterface && $choice->getStatus() == 0) {
  459. return $choice . ' [hors ligne]';
  460. }
  461. return $choice;
  462. },
  463. 'required' => $passedOptions['required'],
  464. 'choice_attr' => $passedOptions['choice_attr'],
  465. )
  466. );
  467. }
  468. } else {
  469. $subChildrens = $child->all();
  470. if (count($subChildrens)) {
  471. $this->loopFormField($child, $subChildrens);
  472. }
  473. }
  474. }
  475. }
  476. protected function editAction()
  477. {
  478. $this->dispatch(EasyAdminEvents::PRE_EDIT);
  479. $id = $this->request->query->get('id');
  480. $easyadmin = $this->request->attributes->get('easyadmin');
  481. $entity = $easyadmin['item'];
  482. if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
  483. $newValue = 'true' === mb_strtolower($this->request->query->get('newValue'));
  484. $fieldsMetadata = $this->entity['list']['fields'];
  485. if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
  486. throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property));
  487. }
  488. $this->updateEntityProperty($entity, $property, $newValue);
  489. $this->utils->addFlash('success', 'success.common.fieldChange');
  490. $response['flashMessages'] = $this->utils->getFlashMessages();
  491. return new Response(json_encode($response));
  492. }
  493. $fields = $this->entity['edit']['fields'];
  494. $editForm = $this->executeDynamicMethod('create<EntityName>EditForm', [$entity, $fields]);
  495. $deleteForm = $this->createDeleteForm($this->entity['name'], $id);
  496. $editForm->handleRequest($this->request);
  497. if ($editForm->isSubmitted() && $editForm->isValid()) {
  498. $this->processUploadedFiles($editForm);
  499. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  500. $this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
  501. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  502. return $this->redirectToReferrer();
  503. }
  504. $this->dispatch(EasyAdminEvents::POST_EDIT);
  505. $parameters = [
  506. 'form' => $editForm->createView(),
  507. 'entity_fields' => $fields,
  508. 'entity' => $entity,
  509. 'delete_form' => $deleteForm->createView(),
  510. ];
  511. return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
  512. }
  513. /* public function createNewEntity(){
  514. $idDuplicate = $this->request->query->get('duplicate', null);
  515. if($idDuplicate){
  516. $easyadmin = $this->request->attributes->get('easyadmin');
  517. $entity= $this->em->getRepository($easyadmin['entity']['class'])->find($idDuplicate);
  518. $newProductFamily = clone $entity ;
  519. $this->em->persist($newProductFamily) ;
  520. $this->em->flush() ;
  521. }else{
  522. $entityFullyQualifiedClassName = $this->entity['class'];
  523. return new $entityFullyQualifiedClassName();
  524. }
  525. }*/
  526. public function duplicateAction()
  527. {
  528. $id = $this->request->query->get('id');
  529. $refererUrl = $this->request->query->get('referer', '');
  530. $easyadmin = $this->request->attributes->get('easyadmin');
  531. $entity = $this->em->getRepository($easyadmin['entity']['class'])->find($id);
  532. $newEntity = $this->utilsProcess->duplicateEntity($entity);
  533. return $this->redirectToRoute('easyadmin', ['entity' => $easyadmin['entity']['name'], 'action' => 'edit', 'id' => $newEntity->getId(), 'referer' => $refererUrl]);
  534. }
  535. public function duplicateOtherHubAction()
  536. {
  537. $id = $this->request->query->get('id');
  538. $hubAlias = $this->request->query->get('hub');
  539. $refererUrl = $this->request->query->get('referer', '');
  540. $user = $this->security->getUser();
  541. $easyadmin = $this->request->attributes->get('easyadmin');
  542. $entity = $this->em->getRepository($easyadmin['entity']['class'])->find($id);
  543. $hub = $this->em->getRepository(MerchantInterface::class)->findOneByDevAlias($hubAlias);
  544. $newEntity = $this->utilsProcess->duplicateEntityToOtherHub($entity, $hub);
  545. $user->setMerchant($hub);
  546. $this->em->persist($user);
  547. $this->em->flush();
  548. $redirectUrl = $this->generateUrl('easyadmin', ['entity' => $easyadmin['entity']['name'], 'action' => 'edit', 'id' => $newEntity->getId(), 'referer' => $refererUrl]) . '&hubredirection=true';
  549. return $this->redirectToOtherHub($hub, $redirectUrl);
  550. }
  551. public function redirectToOtherHub($hub, $url)
  552. {
  553. if (strpos($_SERVER['HTTP_HOST'], 'localhost') !== false) {
  554. return $this->redirect($url);
  555. } else {
  556. return $this->redirect($hub->getMerchantConfig('url') . substr($url, 1));
  557. }
  558. }
  559. }