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.

ProductFamilyController.php 28KB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. <?php
  2. namespace Lc\ShopBundle\Controller\Backend;
  3. use App\Entity\Product;
  4. use Doctrine\ORM\EntityManagerInterface;
  5. use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
  6. use FOS\UserBundle\Model\UserManagerInterface;
  7. use Lc\ShopBundle\Context\ImageInterface;
  8. use Lc\ShopBundle\Context\OrderShopInterface;
  9. use Lc\ShopBundle\Context\ProductCategoryInterface;
  10. use Lc\ShopBundle\Context\ProductFamilyInterface;
  11. use Lc\ShopBundle\Context\ReductionCatalogInterface;
  12. use Lc\ShopBundle\Context\TaxRateInterface;
  13. use Lc\ShopBundle\Form\Backend\Common\AbstractEditPositionType;
  14. use Lc\ShopBundle\Form\Backend\Common\ReductionCatalogType;
  15. use Lc\ShopBundle\Form\Backend\ProductFamily\ProductType;
  16. use Lc\ShopBundle\Model\ProductFamily;
  17. use Lc\ShopBundle\Services\UtilsManager;
  18. use Mailjet\MailjetSwiftMailer\SwiftMailer\MailjetTransport;
  19. use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
  20. use Symfony\Component\Form\Extension\Core\Type\CollectionType;
  21. use Symfony\Component\Form\Extension\Core\Type\HiddenType;
  22. use Symfony\Component\Form\Extension\Core\Type\NumberType;
  23. use Symfony\Component\Form\FormError;
  24. use Symfony\Component\HttpFoundation\Response;
  25. use Symfony\Component\Security\Core\Security;
  26. use Symfony\Contracts\Translation\TranslatorInterface;
  27. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  28. class ProductFamilyController extends AdminController
  29. {
  30. private $taxRateClass;
  31. private $choicesTaxRateParam;
  32. private $choicesSupplierTaxRateParam;
  33. private $parameterBag ;
  34. public function __construct(Security $security, UserManagerInterface $userManager, EntityManagerInterface $em,
  35. MailjetTransport $mailjetTransport, UtilsManager $utilsManager, TranslatorInterface $translator,
  36. ParameterBagInterface $parameterBag)
  37. {
  38. parent::__construct($security, $userManager, $em, $mailjetTransport, $utilsManager, $translator);
  39. $this->parameterBag = $parameterBag ;
  40. }
  41. public function createEntityFormBuilder($entity, $view, $override = true)
  42. {
  43. $formBuilder = parent::createEntityFormBuilder($entity, $view, false);
  44. $class = $this->em->getClassMetadata(ProductCategoryInterface::class);
  45. $this->taxRateClass = $this->em->getClassMetadata(TaxRateInterface::class);
  46. //$formBuilder->add('productCategories', ProductFamilyCategoriesType::class);
  47. $reductionCatalogRepo = $this->em->getRepository(ReductionCatalogInterface::class);
  48. $reductionCatalogClass = $this->em->getClassMetadata(ReductionCatalogInterface::class);
  49. $reductionCatalog = $reductionCatalogRepo->findOneBy(array('status' => false, 'productFamily' => $entity));
  50. if ($reductionCatalog == null) $reductionCatalog = new $reductionCatalogClass->name;
  51. $formBuilder->add('reductionCatalog', ReductionCatalogType::class, array(
  52. 'mapped' => false,
  53. 'data' => $reductionCatalog
  54. ));
  55. $formBuilder->add('stayOnPage', HiddenType::class, array(
  56. 'required' => false,
  57. 'mapped' => false,
  58. ));
  59. $formBuilder->add('warningMessageType', ChoiceType::class, array(
  60. 'choices' => array(
  61. 'field.default.warningMessageTypeOptions.' . ProductFamily::WARNING_MESSAGE_TYPE_SUCCESS => ProductFamily::WARNING_MESSAGE_TYPE_SUCCESS,
  62. 'field.default.warningMessageTypeOptions.' . ProductFamily::WARNING_MESSAGE_TYPE_ERROR => ProductFamily::WARNING_MESSAGE_TYPE_ERROR,
  63. 'field.default.warningMessageTypeOptions.' . ProductFamily::WARNING_MESSAGE_TYPE_WARNING => ProductFamily::WARNING_MESSAGE_TYPE_WARNING,
  64. 'field.default.warningMessageTypeOptions.' . ProductFamily::WARNING_MESSAGE_TYPE_INFO => ProductFamily::WARNING_MESSAGE_TYPE_INFO
  65. ),
  66. 'translation_domain' => 'lcshop',
  67. 'multiple' => false,
  68. 'expanded' => false,
  69. 'required' => false
  70. ));
  71. $formBuilder->add('behaviorCountStock', ChoiceType::class, array(
  72. 'empty_data' => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT_FAMILY,
  73. 'choices' => array(
  74. 'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE,
  75. 'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT_FAMILY => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT_FAMILY,
  76. 'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT => ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT,
  77. 'field.ProductFamily.behaviorCountStockOptions.' . ProductFamily::BEHAVIOR_COUNT_STOCK_UNLIMITED => ProductFamily::BEHAVIOR_COUNT_STOCK_UNLIMITED
  78. ),
  79. 'translation_domain' => 'lcshop',
  80. 'multiple' => false,
  81. 'expanded' => true
  82. ));
  83. $formBuilder->add('behaviorAddToCart', ChoiceType::class, array(
  84. 'data' => $entity->getBehaviorAddToCart() ? $entity->getBehaviorAddToCart() : 'simple',
  85. 'choices' => array(
  86. 'field.ProductFamily.behaviorAddToCartOptions.' . ProductFamily::BEHAVIOR_ADD_TO_CART_SIMPLE => ProductFamily::BEHAVIOR_ADD_TO_CART_SIMPLE,
  87. 'field.ProductFamily.behaviorAddToCartOptions.' . ProductFamily::BEHAVIOR_ADD_TO_CART_MULTIPLE => ProductFamily::BEHAVIOR_ADD_TO_CART_MULTIPLE
  88. ),
  89. 'translation_domain' => 'lcshop',
  90. 'multiple' => false,
  91. 'expanded' => true
  92. ));
  93. $formBuilder->add('behaviorPrice', ChoiceType::class, array(
  94. 'empty_data' => 'by-piece',
  95. 'choices' => array(
  96. 'field.ProductFamily.behaviorPriceOptions.' . ProductFamily::BEHAVIOR_PRICE_BY_PIECE => ProductFamily::BEHAVIOR_PRICE_BY_PIECE,
  97. 'field.ProductFamily.behaviorPriceOptions.' . ProductFamily::BEHAVIOR_PRICE_BY_REFERENCE_UNIT => ProductFamily::BEHAVIOR_PRICE_BY_REFERENCE_UNIT
  98. ),
  99. 'translation_domain' => 'lcshop',
  100. 'multiple' => false,
  101. 'expanded' => true
  102. ));
  103. $formBuilder->add('multiplyingFactor', NumberType::class, array(
  104. 'mapped' => false,
  105. 'data' => floatval($this->merchantUtils->getMerchantConfig('multiplying-factor')),
  106. ));
  107. $formBuilder->add('propertyOrganicLabel', ChoiceType::class, array(
  108. 'choices' => array(
  109. 'field.ProductFamily.organicLabelOptions.' . ProductFamily::PROPERTY_ORGANIC_LABEL_AB => ProductFamily::PROPERTY_ORGANIC_LABEL_AB,
  110. 'field.ProductFamily.organicLabelOptions.' . ProductFamily::PROPERTY_ORGANIC_LABEL_NP => ProductFamily::PROPERTY_ORGANIC_LABEL_NP,
  111. 'field.ProductFamily.organicLabelOptions.' . ProductFamily::PROPERTY_ORGANIC_LABEL_HVE => ProductFamily::PROPERTY_ORGANIC_LABEL_HVE
  112. ),
  113. 'translation_domain' => 'lcshop',
  114. 'multiple' => false,
  115. 'expanded' => false,
  116. 'required' => false
  117. ));
  118. $formBuilder->add('typeExpirationDate', ChoiceType::class, array(
  119. 'choices' => array(
  120. 'field.default.' . ProductFamily::TYPE_EXPIRATION_DATE_DLC => ProductFamily::TYPE_EXPIRATION_DATE_DLC,
  121. 'field.default.' . ProductFamily::TYPE_EXPIRATION_DATE_DDM => ProductFamily::TYPE_EXPIRATION_DATE_DDM,
  122. 'field.default.' . ProductFamily::TYPE_EXPIRATION_DATE_DLUO => ProductFamily::TYPE_EXPIRATION_DATE_DLUO
  123. ),
  124. 'translation_domain' => 'lcshop',
  125. 'multiple' => false,
  126. 'expanded' => true,
  127. 'required' => false
  128. ));
  129. $formBuilder->add('behaviorStockWeek', ChoiceType::class, array(
  130. 'choices' => array(
  131. 'field.ProductFamily.behaviorStockWeekOptions.' . ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE => ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE,
  132. 'field.ProductFamily.behaviorStockWeekOptions.' . ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE_VALIDATION => ProductFamily::BEHAVIOR_STOCK_WEEK_RENEWABLE_VALIDATION,
  133. 'field.ProductFamily.behaviorStockWeekOptions.' . ProductFamily::BEHAVIOR_STOCK_WEEK_NON_RENEWABLE => ProductFamily::BEHAVIOR_STOCK_WEEK_NON_RENEWABLE
  134. ),
  135. 'translation_domain' => 'lcshop',
  136. 'multiple' => false,
  137. 'expanded' => true,
  138. 'required' => true
  139. ));
  140. $formBuilder->add('behaviorExpirationDate', ChoiceType::class, array(
  141. 'choices' => array(
  142. 'field.ProductFamily.behaviorExpirationDateOptions.' . ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT_FAMILY => ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT_FAMILY,
  143. 'field.ProductFamily.behaviorExpirationDateOptions.' . ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT => ProductFamily::BEHAVIOR_EXPIRATION_DATE_BY_PRODUCT
  144. ),
  145. 'translation_domain' => 'lcshop',
  146. 'multiple' => false,
  147. 'expanded' => true,
  148. 'required' => false
  149. ));
  150. $formBuilder->add('products', CollectionType::class, array(
  151. 'label' => 'Déclinaisons',
  152. 'entry_type' => ProductType::class,
  153. 'entry_options' => ['label' => false],
  154. 'allow_add' => true,
  155. 'allow_delete' => true,
  156. 'required' => true
  157. )
  158. );
  159. $formBuilder = $this->overrideFormBuilder($formBuilder, $entity, $view);
  160. return $formBuilder;
  161. }
  162. public function updateProductFamilyEntity($entity, $editForm = false)
  163. {
  164. if ($editForm) {
  165. $this->processReductionCatalog($entity, $editForm);
  166. $this->processCategories($entity);
  167. $this->processProducts($entity);
  168. $this->processPrice($entity);
  169. }
  170. parent::updateEntity($entity);
  171. $this->orderUtils->updatePriceByProductFamily($entity);
  172. }
  173. public function persistProductFamilyEntity($entity, $newForm)
  174. {
  175. $this->processReductionCatalog($entity, $newForm);
  176. $this->processCategories($entity);
  177. $this->processProducts($entity);
  178. $this->processPrice($entity);
  179. $this->em->persist($entity);
  180. $this->em->flush();
  181. }
  182. protected function processReductionCatalog($entity, $editForm)
  183. {
  184. $reductionCatalog = $editForm->get('reductionCatalog')->getData();
  185. if ($reductionCatalog instanceof ReductionCatalogInterface) {
  186. if ($reductionCatalog->getValue() && $reductionCatalog->getBehaviorTaxRate() && $reductionCatalog->getUnit()) {
  187. $reductionCatalog->setMerchant($entity->getMerchant());
  188. $reductionCatalog->setStatus($editForm->get('activeReductionCatalog')->getData());
  189. $reductionCatalog->setProductFamily($entity);
  190. $this->em->persist($reductionCatalog);
  191. }
  192. }
  193. }
  194. protected function processPrice($entity)
  195. {
  196. if ($entity->getBehaviorPrice() == 'by-piece') {
  197. $entity->setPriceByRefUnit(null);
  198. $entity->setBuyingPriceByRefUnit(null);
  199. } else if ($entity->getBehaviorPrice() == 'by-reference-unit') {
  200. $entity->setPrice(null);
  201. $entity->setBuyingPrice(null);
  202. }
  203. }
  204. protected function processProducts($entity, $clone = false)
  205. {
  206. //si il existe un et un seul produit pour ce product family n'ajoute rien supprime rien
  207. if (count($entity->getProducts()) == 0) {
  208. $product = new Product();
  209. $product->setProductFamily($entity);
  210. $this->em->persist($product);
  211. $entity->addProduct($product);
  212. } else {
  213. foreach ($entity->getProducts() as $i => $product) {
  214. if ($clone) {
  215. $newProduct = clone $product;
  216. $newProduct->setProductFamily($entity);
  217. $this->em->persist($newProduct);
  218. $entity->addProduct($newProduct);
  219. } else {
  220. $product->setProductFamily($entity);
  221. $this->em->persist($product);
  222. $entity->addProduct($product);
  223. }
  224. }
  225. }
  226. }
  227. protected function processCategories(ProductFamilyInterface $entity)
  228. {
  229. $productCategoryRepository = $this->getDoctrine()->getRepository(ProductCategoryInterface::class);
  230. $productCategories = $entity->getProductCategories();
  231. $entity->initProductCategories();
  232. foreach ($productCategories as $key => $bool) {
  233. if (is_bool($bool) && $bool) {
  234. if (strpos($key, 'category_children_') !== false) {
  235. $idCategory = (int)str_replace('category_children_', '', $key);
  236. } else {
  237. $idCategory = (int)str_replace('category_', '', $key);
  238. }
  239. $category = $productCategoryRepository->find($idCategory);
  240. $entity->addProductCategory($category);
  241. }
  242. }
  243. }
  244. protected function editAction()
  245. {
  246. $this->dispatch(EasyAdminEvents::PRE_EDIT);
  247. $id = $this->request->query->get('id');
  248. $easyadmin = $this->request->attributes->get('easyadmin');
  249. $entity = $easyadmin['item'];
  250. if ($this->request->isXmlHttpRequest() && $property = $this->request->query->get('property')) {
  251. $newValue = 'true' === mb_strtolower($this->request->query->get('newValue'));
  252. $fieldsMetadata = $this->entity['list']['fields'];
  253. if (!isset($fieldsMetadata[$property]) || 'toggle' !== $fieldsMetadata[$property]['dataType']) {
  254. throw new \RuntimeException(sprintf('The type of the "%s" property is not "toggle".', $property));
  255. }
  256. $this->updateEntityProperty($entity, $property, $newValue);
  257. $this->utils->addFlash('success', 'success.common.fieldChange');
  258. $response['flashMessages'] = $this->utils->getFlashMessages();
  259. return new Response(json_encode($response));
  260. }
  261. $fields = $this->entity['edit']['fields'];
  262. $editForm = $this->executeDynamicMethod('create<EntityName>EditForm', [$entity, $fields]);
  263. $deleteForm = $this->createDeleteForm($this->entity['name'], $id);
  264. $sortableProductsField = array();
  265. foreach ($editForm->get('products')->getData() as $k => $product) {
  266. $sortableProductsField[$product->getPosition()] = $k;
  267. }
  268. ksort($sortableProductsField);
  269. $editForm->handleRequest($this->request);
  270. if ($editForm->isSubmitted() && count($entity->getProductCategories()) == 0) {
  271. $editForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  272. }
  273. if ($editForm->isSubmitted() && $editForm->isValid() && count($entity->getProductCategories()) > 0) {
  274. $this->processUploadedFiles($editForm);
  275. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  276. $this->executeDynamicMethod('update<EntityName>Entity', [$entity, $editForm]);
  277. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  278. $this->utils->addFlash('success', 'Produit sauvegardé');
  279. if ($editForm->get('stayOnPage')->getData() != "false" || $this->request->get('submitAndStay') !== null) {
  280. $refererUrl = $this->request->query->get('referer', '');
  281. return $this->redirectToRoute('easyadmin', ['entity' => 'ProductFamily', 'action' => 'edit', 'id' => $id, 'referer' => $refererUrl]);
  282. } else {
  283. return $this->redirectToReferrer();
  284. }
  285. }
  286. $this->dispatch(EasyAdminEvents::POST_EDIT);
  287. $parameters = [
  288. 'form' => $editForm->createView(),
  289. 'entity_fields' => $fields,
  290. 'entity' => $entity,
  291. 'delete_form' => $deleteForm->createView(),
  292. 'sortableProductsField' => $sortableProductsField,
  293. 'totalProductOrdered' => $this->orderUtils->getTotalProductOrderedLastWeeks($entity)
  294. ];
  295. return $this->executeDynamicMethod('render<EntityName>Template', ['edit', $this->entity['templates']['edit'], $parameters]);
  296. }
  297. protected function newAction()
  298. {
  299. $this->dispatch(EasyAdminEvents::PRE_NEW);
  300. $entity = $this->executeDynamicMethod('createNew<EntityName>Entity');
  301. $easyadmin = $this->request->attributes->get('easyadmin');
  302. $easyadmin['item'] = $entity;
  303. $this->request->attributes->set('easyadmin', $easyadmin);
  304. $fields = $this->entity['new']['fields'];
  305. $newForm = $this->executeDynamicMethod('create<EntityName>NewForm', [$entity, $fields]);
  306. $newForm->handleRequest($this->request);
  307. if ($newForm->isSubmitted() && array_search(true, $newForm->get('productCategories')->getData()->toArray()) === false) {
  308. $newForm->get('productCategories')->addError(new FormError('Vous devez choisir au moins une catégorie'));
  309. }
  310. if ($newForm->isSubmitted() && $newForm->isValid() && array_search(true, $newForm->get('productCategories')->getData()->toArray()) !== false) {
  311. $this->processUploadedFiles($newForm);
  312. $this->dispatch(EasyAdminEvents::PRE_PERSIST, ['entity' => $entity]);
  313. $this->executeDynamicMethod('persist<EntityName>Entity', [$entity, $newForm]);
  314. $this->dispatch(EasyAdminEvents::POST_PERSIST, ['entity' => $entity]);
  315. if ($newForm->get('stayOnPage')->getData() != "false" || $this->request->get('submitAndStay') !== null) {
  316. return $this->redirectToRoute('easyadmin', ['entity' => 'ProductFamily', 'action' => 'edit', 'id' => $entity->getId()]);
  317. } else {
  318. return $this->redirectToReferrer();
  319. }
  320. }
  321. $this->dispatch(EasyAdminEvents::POST_NEW, [
  322. 'entity_fields' => $fields,
  323. 'form' => $newForm,
  324. 'entity' => $entity
  325. ]);
  326. $productCategoryRepository = $this->getDoctrine()->getRepository(ProductCategoryInterface::class);
  327. $categories = $productCategoryRepository->findAllParents();
  328. $parameters = [
  329. 'form' => $newForm->createView(),
  330. 'entity_fields' => $fields,
  331. 'entity' => $entity,
  332. 'categories' => $categories,
  333. 'sortableProductsField' => array(),
  334. 'totalProductOrdered' => array()
  335. ];
  336. return $this->executeDynamicMethod('render<EntityName>Template', ['new', $this->entity['templates']['new'], $parameters]);
  337. }
  338. public function duplicateAction()
  339. {
  340. $id = $this->request->query->get('id');
  341. $refererUrl = $this->request->query->get('referer', '');
  342. $easyadmin = $this->request->attributes->get('easyadmin');
  343. $entity = $this->em->getRepository($easyadmin['entity']['class'])->find($id);
  344. $newProductFamily = clone $entity;
  345. if ($easyadmin['entity']['name'] == "ProductFamily") {
  346. $this->processProducts($newProductFamily, true);
  347. }
  348. if($newProductFamily instanceof ImageInterface) {
  349. $basePath = $this->parameterBag->get('kernel.project_dir').'/public/uploads/images/' ;
  350. $imageProductFamily = 'produits/'.md5(time()).'.jpg' ;
  351. copy($basePath.$entity->getImage(), $basePath.$imageProductFamily) ;
  352. $newProductFamily->setImage($imageProductFamily);
  353. }
  354. $this->em->persist($newProductFamily);
  355. $this->em->flush();
  356. return $this->redirectToRoute('easyadmin', ['entity' => $easyadmin['entity']['name'], 'action' => 'edit', 'id' => $newProductFamily->getId(), 'referer' => $refererUrl]);
  357. }
  358. //hack utilisé pour filter sur les catégories lors du tri des produits par sous cat
  359. //A améliorer à l'occas
  360. protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
  361. {
  362. $productCategoryId = false;
  363. if (isset($dqlFilter['productCategoryId'])) $productCategoryId = $dqlFilter['productCategoryId'];
  364. if(isset($dqlFilter['filter']))$dqlFilter = $dqlFilter['filter'];
  365. $queryBuilder = parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
  366. $queryBuilder->leftJoin('entity.productCategories', 'product_categories');
  367. if ($productCategoryId) {
  368. $queryBuilder->andWhere('product_categories.id = :cat');
  369. $queryBuilder->setParameter('cat', $productCategoryId);
  370. }
  371. return $queryBuilder;
  372. }
  373. public function sortByProductCategoryAction(){
  374. $this->dispatch(EasyAdminEvents::PRE_LIST);
  375. $entity = null;
  376. //Replace this with query builder function, do not use finAll of easyAdmin
  377. if ($this->request->query->get('productCategoryId')) {
  378. if(!is_array($this->entity['list']['dql_filter'])) {
  379. $this->entity['list']['dql_filter'] = array('filter' => $this->entity['list']['dql_filter']);
  380. }
  381. $this->entity['list']['dql_filter']['productCategoryId'] = $this->request->query->get('productCategoryId');
  382. $easyadmin = $this->request->attributes->get('easyadmin');
  383. $entity = $easyadmin['item'];
  384. }else{
  385. throw new \ErrorException('Action impossible') ;
  386. }
  387. if ($this->entity['list']['dql_filter']['filter']) $this->entity['list']['dql_filter']['filter'] .= sprintf(' AND entity.status = 1');
  388. else $this->entity['list']['dql_filter']['filter'] .= sprintf(' entity.status = 1');
  389. $fields = $this->entity['list']['fields'];
  390. $paginator = $this->findAll($this->entity['class'], $this->request->query->get('page', 1), 500, 'position', 'asc', $this->entity['list']['dql_filter']);
  391. $this->dispatch(EasyAdminEvents::POST_LIST, ['paginator' => $paginator]);
  392. $positionForm = $this->createFormBuilder(array('entities', $paginator->getCurrentPageResults()))
  393. ->add('entities', CollectionType::class, array(
  394. 'required' => true,
  395. 'allow_add' => true,
  396. 'entry_type' => AbstractEditPositionType::class,
  397. ))
  398. ->getForm();
  399. $positionForm->handleRequest($this->request);
  400. if ($positionForm->isSubmitted() && $positionForm->isValid()) {
  401. $class = $this->entity['class'];
  402. $repo = $this->em->getRepository($class);
  403. $latsPos = 0;
  404. foreach ($positionForm->get('entities')->getData() as $elm) {
  405. $this->dispatch(EasyAdminEvents::PRE_UPDATE, ['entity' => $entity]);
  406. $entity = $repo->find($elm['id']);
  407. $entity->setPosition($elm['position']);
  408. $this->em->persist($entity);
  409. $this->dispatch(EasyAdminEvents::POST_UPDATE, ['entity' => $entity]);
  410. $latsPos = $elm['position'];
  411. }
  412. //die();
  413. //to do récupérer les élements hors ligne et incrémenter position
  414. /*foreach ($repo->findBy(array('status'=> false)) as $offlineEntity) {
  415. $latsPos++;
  416. $offlineEntity->setPosition($latsPos);
  417. $this->em->persist($offlineEntity);
  418. }*/
  419. $this->em->flush();
  420. $this->addFlash('success', 'Position modifié', array(), 'mweb');
  421. return $this->redirectToReferrer();
  422. }
  423. $parameters = [
  424. 'paginator' => $paginator,
  425. 'fields' => $fields,
  426. 'batch_form' => $this->createBatchForm($this->entity['name'])->createView(),
  427. 'delete_form_template' => $this->createDeleteForm($this->entity['name'], '__id__')->createView(),
  428. 'postion_form' => $positionForm->createView(),
  429. 'entity' => $entity,
  430. 'sortable' => true
  431. ];
  432. return $this->executeDynamicMethod('render<EntityName>Template', ['sortable', "@LcShop/backend/default/sortable.html.twig", $parameters]);
  433. }
  434. }