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.

787 satır
40KB

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