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.

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