Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

763 lines
38KB

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