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.

710 satır
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, 'TODAYSTART')) {
  120. $date = new \DateTime();
  121. $dqlFilter = sprintf(str_replace('TODAYSTART', $date->format('Y-m-d').' 00:00:00', $dqlFilter));
  122. }
  123. if ($pos = strpos($dqlFilter, 'TODAYEND')) {
  124. $date = new \DateTime();
  125. $dqlFilter = sprintf(str_replace('TODAYEND', $date->format('Y-m-d').' 23:59:59', $dqlFilter));
  126. }
  127. if ($pos = strpos($dqlFilter, 'sectionLunch')) {
  128. $dqlFilter = sprintf(str_replace('sectionLunch', $this->sectionUtils->getSection('lunch')->getId(), $dqlFilter));
  129. } else if ($pos = strpos($dqlFilter, 'sectionMarket')) {
  130. $dqlFilter = sprintf(str_replace('sectionMarket', $this->sectionUtils->getSection('market')->getId(), $dqlFilter));
  131. }
  132. if (new $entityClass instanceof StatusInterface && strpos($dqlFilter, 'entity.status') === false) {
  133. if ($dqlFilter) $dqlFilter .= sprintf(' AND entity.status > = 0');
  134. else $dqlFilter .= sprintf(' entity.status > = 0');
  135. }
  136. return $dqlFilter;
  137. }
  138. protected function commonQueryFilter($entityClass, $queryBuilder)
  139. {
  140. if (new $entityClass instanceof FilterMultipleMerchantsInterface) {
  141. $queryBuilder->andWhere(':currentMerchant MEMBER OF entity.merchants')
  142. ->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  143. }
  144. }
  145. protected function createSearchQueryBuilder($entityClass, $searchQuery, array $searchableFields, $sortField = null, $sortDirection = null, $dqlFilter = null)
  146. {
  147. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter);
  148. $queryBuilder = parent::createSearchQueryBuilder($entityClass, $searchQuery, $searchableFields, $sortField, $sortDirection, $dqlFilter);
  149. $this->commonQueryFilter($entityClass, $queryBuilder);
  150. return $queryBuilder;
  151. }
  152. protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
  153. {
  154. $dqlFilter = $this->commonDqlFilterQueryBuilder($entityClass, $dqlFilter);
  155. $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
  156. $this->commonQueryFilter($entityClass, $queryBuilder);
  157. $listFields = $this->entity['list']['fields'];
  158. $this->filtersForm = $this->createForm(ListFilterType::class, null, array(
  159. 'fields' => $listFields,
  160. 'method' => 'get',
  161. 'entity_name' => $this->entity['name'],
  162. //'entityClass' => $this->entity['class'],
  163. 'entity_class' => $this->entity['class']
  164. ));
  165. $this->filtersForm->handleRequest($this->request);
  166. if ($this->filtersForm->isSubmitted() && $this->filtersForm->isValid()) {
  167. foreach ($listFields as $field) {
  168. if ($this->filtersForm->has($field['property'])) {
  169. switch ($field['dataType']) {
  170. case 'option':
  171. case 'integer':
  172. case 'text':
  173. case 'string':
  174. case 'toggle':
  175. $filter = $this->filtersForm->get($field['property'])->getData();
  176. if ($filter !== null) {
  177. $queryBuilder->andWhere('entity.' . $field['property'] . ' LIKE :' . $field['property'] . '');
  178. $queryBuilder->setParameter($field['property'], '%' . $filter . '%');
  179. }
  180. break;
  181. case 'association' :
  182. $filter = $this->filtersForm->get($field['property'])->getData();
  183. if ($filter !== null) {
  184. if ($field['type_options']['multiple']) {
  185. $queryBuilder->andWhere(':' . $field['property'] . ' MEMBER OF entity.' . $field['property'] . '');
  186. } else {
  187. $queryBuilder->andWhere('entity.' . $field['property'] . ' = :' . $field['property'] . '');
  188. }
  189. if ($filter instanceof TreeInterface && $filter->getParent() == null) {
  190. $queryBuilder->setParameter($field['property'], array_merge(array($filter), $filter->getChildrens()->toArray()));
  191. } else {
  192. $queryBuilder->setParameter($field['property'], $filter);
  193. }
  194. }
  195. break;
  196. case 'datetime':
  197. case 'date':
  198. $dateStart = $this->filtersForm->get($field['property'])->get('dateStart')->getData();
  199. $dateEnd = $this->filtersForm->get($field['property'])->get('dateEnd')->getData();
  200. if ($dateStart) $queryBuilder->andWhere('entity.' . $field['property'] . ' >= :dateStart')->setParameter('dateStart', $dateStart);
  201. if ($dateEnd) $queryBuilder->andWhere('entity.' . $field['property'] . ' <= :dateEnd')->setParameter('dateEnd', $dateEnd);
  202. }
  203. }
  204. }
  205. }
  206. //TODO déplacer dans LC
  207. if($this->entity['name']== 'OrderShopLunch' || $this->entity['name']== 'OrderShopLunchDay'){
  208. $queryBuilder->addOrderBy('entity.user', 'asc');
  209. }
  210. return $queryBuilder;
  211. }
  212. public function renderTemplate($actionName, $templatePath, array $parameters = [])
  213. {
  214. $reminderRepo = $this->em->getRepository(ReminderInterface::class);
  215. $easyadmin = $this->request->attributes->get('easyadmin');
  216. $entityName = $easyadmin['entity']['name'];
  217. $id = null;
  218. if ($easyadmin['item']) $id = $easyadmin['item']->getId();
  219. $user = $this->security->getUser();
  220. $reminders = array('reminders' => $reminderRepo->findByEasyAdminConfigAndUser($actionName, $entityName, $user, $id));
  221. if ($actionName == 'list') {
  222. if ($this->filtersForm === null) {
  223. $options['fields'] = $parameters['fields'];
  224. $options['method'] = 'get';
  225. $this->filtersForm = $this->createForm(ListFilterType::class, null, $options);
  226. }
  227. $parameters = array_merge(
  228. $parameters,
  229. array(
  230. 'filters_form' => $this->filtersForm->createView()
  231. )
  232. );
  233. }
  234. $parameters = array_merge(
  235. $parameters,
  236. $this->getTwigExtraParameters(),
  237. $reminders
  238. );
  239. return parent::renderTemplate($actionName, $templatePath, $parameters);
  240. }
  241. public function getTwigExtraParameters()
  242. {
  243. $repositoryMerchant = $this->getDoctrine()->getRepository(MerchantInterface::class);
  244. $merchants = $repositoryMerchant->findAll();
  245. $user = $this->security->getUser();
  246. return [
  247. 'merchants' => $merchants,
  248. 'current_merchant' => ($user && $user->getMerchant()) ? $user->getMerchant() : null,
  249. ];
  250. }
  251. public function listChildrenAction()
  252. {
  253. $this->dispatch(EasyAdminEvents::PRE_LIST);
  254. $id = $this->request->query->get('id');
  255. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  256. $easyadmin = $this->request->attributes->get('easyadmin');
  257. $entity = $easyadmin['item'];
  258. $fields = $this->entity['list']['fields'];
  259. $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']);
  260. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  261. $parameters = [
  262. 'paginator' => $paginator,
  263. 'fields' => $fields,
  264. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  265. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  266. 'entity' => $entity,
  267. ];
  268. return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
  269. }
  270. protected function getListParam($param, $default =null){
  271. $entityName = $this->entity['name'];
  272. $sessionParam = $entityName.$param;
  273. //CUSTOM
  274. if($param == 'maxResults'){
  275. $val = $this->entity['list']['max_results'];
  276. }else{
  277. $val = $this->request->query->get($param, $default);
  278. }
  279. if(isset($_GET[$param])){
  280. $val = $this->request->query->get($param);
  281. $this->session->set($sessionParam, $val);
  282. }else if($this->session->get($sessionParam)){
  283. $val = $this->session->get($sessionParam);
  284. $this->request->query->set($param, $val);
  285. }
  286. return $val;
  287. }
  288. protected function listAction()
  289. {
  290. $this->dispatch(EasyAdminEvents::PRE_LIST);
  291. $fields = $this->entity['list']['fields'];
  292. $paginator = $this->findAll($this->entity['class'], $this->getListParam('page', 1), $this->getListParam('maxResults'), $this->getListParam('sortField'), $this->getListParam('sortDirection'), $this->entity['list']['dql_filter']);
  293. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  294. $parameters = [
  295. 'paginator' => $paginator,
  296. 'fields' => $fields,
  297. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  298. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  299. ];
  300. return $this->executeDynamicMethod('render<EntityName>Template', ['list', $this->entity['templates']['list'], $parameters]);
  301. }
  302. public function sortAction()
  303. {
  304. $this->dispatch(EasyAdminEvents::PRE_LIST);
  305. $entity = null;
  306. //Replace this with query builder function, do not use finAll of easyAdmin
  307. if ($this->request->query->get('id')) {
  308. $id = $this->request->query->get('id');
  309. $this->entity['list']['dql_filter'] = "entity.parent = " . $id;
  310. $easyadmin = $this->request->attributes->get('easyadmin');
  311. $entity = $easyadmin['item'];
  312. }
  313. if ($this->entity['list']['dql_filter']) $this->entity['list']['dql_filter'] .= sprintf(' AND entity.status = 1');
  314. else $this->entity['list']['dql_filter'] .= sprintf(' entity.status = 1');
  315. $fields = $this->entity['list']['fields'];
  316. $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']);
  317. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  318. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  319. ->add('entities', CollectionType::class, array(
  320. 'required' => true,
  321. 'allow_add' => true,
  322. 'entry_type' => AbstractEditPositionType::class,
  323. ))
  324. ->getForm();
  325. $positionForm->handleRequest($this->request);
  326. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  327. $class = $this->entity['class'];
  328. $repo = $this->em->getRepository($class);
  329. $latsPos = 0;
  330. foreach ($positionForm->get('entities')->getData() as $elm) {
  331. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  332. $entity = $repo->find($elm['id']);
  333. $entity->setPosition($elm['position']);
  334. $this->em->persist($entity);
  335. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  336. $latsPos = $elm['position'];
  337. }
  338. //die();
  339. //die();
  340. //to do récupérer les élements hors ligne et incrémenter position
  341. /*foreach ($repo->findBy(array('status'=> false)) as $offlineEntity) {
  342. $latsPos++;
  343. $offlineEntity->setPosition($latsPos);
  344. $this->em->persist($offlineEntity);
  345. }*/
  346. $this->em->flush();
  347. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  348. return $this->redirectToReferrer();
  349. }
  350. $parameters = [
  351. 'paginator' => $paginator,
  352. 'fields' => $fields,
  353. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  354. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  355. 'postion_form' => $positionForm->createView(),
  356. 'entity' => $entity,
  357. 'sortable' => true
  358. ];
  359. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  360. }
  361. public function createEntityFormBuilder($entity, $view, $override = true)
  362. {
  363. $formBuilder = parent::createEntityFormBuilder($entity, $view);
  364. if ($override) $formBuilder = $this->overrideFormBuilder($formBuilder, $entity, $view);
  365. return $formBuilder;
  366. }
  367. public function overrideFormBuilder($formBuilder, $entity, $view)
  368. {
  369. $id = (null !== $entity->getId()) ? $entity->getId() : 0;
  370. if ($entity instanceof SeoInterface) {
  371. $formBuilder->add('metaTitle', TextType::class, array(
  372. 'required' => false,
  373. 'translation_domain' => 'lcshop'
  374. )
  375. );
  376. $formBuilder->add('metaDescription', TextareaType::class, array(
  377. 'required' => false,
  378. 'translation_domain' => 'lcshop'
  379. )
  380. );
  381. /*$formBuilder->add('oldUrls', TextareaType::class, array(
  382. 'required' => false,
  383. 'translation_domain' => 'lcshop'
  384. )
  385. );*/
  386. }
  387. if ($entity instanceof StatusInterface) {
  388. $formBuilder->add('status', ChoiceType::class, array(
  389. 'choices' => array(
  390. 'field.default.statusOptions.offline' => '0',
  391. 'field.default.statusOptions.online' => '1'
  392. ),
  393. 'expanded' => true,
  394. 'required' => true,
  395. 'translation_domain' => 'lcshop'
  396. )
  397. );
  398. }
  399. if ($entity instanceof TreeInterface) {
  400. $formBuilder->add('parent', EntityType::class, array(
  401. 'class' => $this->entity['class'],
  402. 'query_builder' => function (EntityRepository $repo) use ($id) {
  403. return $repo->createQueryBuilder('e')
  404. ->where('e.parent is NULL')
  405. ->andWhere('e.status >= 0')
  406. ->orderBy('e.status', "DESC");
  407. },
  408. 'required' => false,
  409. )
  410. );
  411. }
  412. $formBuilder->addEventListener(FormEvents::POST_SET_DATA, function (FormEvent $event) {
  413. $form = $event->getForm();
  414. $childrens = $form->all();
  415. $this->loopFormField($form, $childrens);
  416. });
  417. return $formBuilder;
  418. }
  419. private function loopFormField($form, $childrens)
  420. {
  421. foreach ($childrens as $child) {
  422. $statusInterface = false;
  423. $treeInterface = false;
  424. $type = $child->getConfig()->getType()->getInnerType();;
  425. if ($type instanceof EntityType) {
  426. $passedOptions = $child->getConfig()->getOptions();
  427. $classImplements = class_implements($passedOptions['class']);
  428. $isFilterMerchantInterface = in_array('Lc\ShopBundle\Context\FilterMerchantInterface', $classImplements);
  429. $isFilterMultipleMerchantsInterface = in_array('Lc\ShopBundle\Context\FilterMultipleMerchantsInterface', $classImplements);
  430. if ($isFilterMerchantInterface || $isFilterMultipleMerchantsInterface) {
  431. if (in_array('Lc\ShopBundle\Context\StatusInterface', $classImplements)) {
  432. $statusInterface = true;
  433. }
  434. if (in_array('Lc\ShopBundle\Context\TreeInterface', $classImplements)) {
  435. $treeInterface = true;
  436. }
  437. $propertyMerchant = 'merchant';
  438. if ($isFilterMultipleMerchantsInterface) {
  439. $propertyMerchant .= 's';
  440. }
  441. $form->add($child->getName(), EntityType::class, array(
  442. 'class' => $this->em->getClassMetadata($passedOptions['class'])->getName(),
  443. 'label' => $passedOptions['label'],
  444. 'expanded' => isset($passedOptions['expanded']) ? $passedOptions['expanded'] : false,
  445. 'multiple' => isset($passedOptions['multiple']) ? $passedOptions['multiple'] : false,
  446. 'placeholder' => '--',
  447. 'translation_domain' => 'lcshop',
  448. 'query_builder' => function (EntityRepository $repo) use ($passedOptions, $propertyMerchant, $statusInterface, $treeInterface, $child) {
  449. $queryBuilder = $repo->createQueryBuilder('e');
  450. $propertyMerchant = 'e.' . $propertyMerchant;
  451. if ($passedOptions['class'] == 'App\Entity\PointSale') {
  452. $queryBuilder->where(':currentMerchant MEMBER OF ' . $propertyMerchant);
  453. } else {
  454. $queryBuilder->where($propertyMerchant . ' = :currentMerchant');
  455. }
  456. if ($statusInterface) {
  457. $queryBuilder->andWhere('e.status >= 0');
  458. }
  459. if ($treeInterface && $child->getName() == 'parent') {
  460. $queryBuilder->andWhere('e.parent is null');
  461. }
  462. $queryBuilder->setParameter(':currentMerchant', $this->getUser()->getMerchant()->getId());
  463. return $queryBuilder;
  464. },
  465. 'choice_label' => function ($choice) {
  466. if ($choice instanceof StatusInterface && $choice->getStatus() == 0) {
  467. return $choice . ' [hors ligne]';
  468. }
  469. return $choice;
  470. },
  471. 'required' => $passedOptions['required'],
  472. 'choice_attr' => $passedOptions['choice_attr'],
  473. )
  474. );
  475. }
  476. } else {
  477. $subChildrens = $child->all();
  478. if (count($subChildrens)) {
  479. $this->loopFormField($child, $subChildrens);
  480. }
  481. }
  482. }
  483. }
  484. protected function editAction()
  485. {
  486. $this->dispatch(EasyAdminEvents::PRE_EDIT);
  487. $id = $this->request->query->get('id');
  488. $easyadmin = $this->request->attributes->get('easyadmin');
  489. $entity = $easyadmin['item'];
  490. if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
  491. $newValue = 'true' === mb_strtolower($this->request->query->get('newValue'));
  492. $fieldsMetadata = $this->entity['list']['fields'];
  493. if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
  494. throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property));
  495. }
  496. $this->updateEntityProperty($entity, $property, $newValue);
  497. $this->utils->addFlash('success', 'success.common.fieldChange');
  498. $response['flashMessages'] = $this->utils->getFlashMessages();
  499. return new Response(json_encode($response));
  500. }
  501. $fields = $this->entity['edit']['fields'];
  502. $editForm = $this->executeDynamicMethod('create<EntityName>EditForm', [$entity, $fields]);
  503. $deleteForm = $this->createDeleteForm($this->entity['name'], $id);
  504. $editForm->handleRequest($this->request);
  505. if ($editForm->isSubmitted() && $editForm->isValid()) {
  506. $this->processUploadedFiles($editForm);
  507. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  508. $this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
  509. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  510. return $this->redirectToReferrer();
  511. }
  512. $this->dispatch(EasyAdminEvents::POST_EDIT);
  513. $parameters = [
  514. 'form' => $editForm->createView(),
  515. 'entity_fields' => $fields,
  516. 'entity' => $entity,
  517. 'delete_form' => $deleteForm->createView(),
  518. ];
  519. return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
  520. }
  521. /* public function createNewEntity(){
  522. $idDuplicate = $this->request->query->get('duplicate', null);
  523. if($idDuplicate){
  524. $easyadmin = $this->request->attributes->get('easyadmin');
  525. $entity= $this->em->getRepository($easyadmin['entity']['class'])->find($idDuplicate);
  526. $newProductFamily = clone $entity ;
  527. $this->em->persist($newProductFamily) ;
  528. $this->em->flush() ;
  529. }else{
  530. $entityFullyQualifiedClassName = $this->entity['class'];
  531. return new $entityFullyQualifiedClassName();
  532. }
  533. }*/
  534. public function duplicateAction()
  535. {
  536. $id = $this->request->query->get('id');
  537. $refererUrl = $this->request->query->get('referer', '');
  538. $easyadmin = $this->request->attributes->get('easyadmin');
  539. $entity = $this->em->getRepository($easyadmin['entity']['class'])->find($id);
  540. $newEntity = $this->utilsProcess->duplicateEntity($entity);
  541. return $this->redirectToRoute('easyadmin', ['entity' => $easyadmin['entity']['name'], 'action' => 'edit', 'id' => $newEntity->getId(), 'referer' => $refererUrl]);
  542. }
  543. public function duplicateOtherHubAction()
  544. {
  545. $id = $this->request->query->get('id');
  546. $hubAlias = $this->request->query->get('hub');
  547. $refererUrl = $this->request->query->get('referer', '');
  548. $user = $this->security->getUser();
  549. $easyadmin = $this->request->attributes->get('easyadmin');
  550. $entity = $this->em->getRepository($easyadmin['entity']['class'])->find($id);
  551. $hub = $this->em->getRepository(MerchantInterface::class)->findOneByDevAlias($hubAlias);
  552. $newEntity = $this->utilsProcess->duplicateEntityToOtherHub($entity, $hub);
  553. $user->setMerchant($hub);
  554. $this->em->persist($user);
  555. $this->em->flush();
  556. $redirectUrl = $this->generateUrl('easyadmin', ['entity' => $easyadmin['entity']['name'], 'action' => 'edit', 'id' => $newEntity->getId(), 'referer' => $refererUrl]) . '&hubredirection=true';
  557. return $this->redirectToOtherHub($hub, $redirectUrl);
  558. }
  559. public function redirectToOtherHub($hub, $url)
  560. {
  561. if (strpos($_SERVER['HTTP_HOST'], 'localhost') !== false) {
  562. return $this->redirect($url);
  563. } else {
  564. return $this->redirect($hub->getMerchantConfig('url') . substr($url, 1));
  565. }
  566. }
  567. }