No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

ProductFamilyController.php 31KB

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