/** * Generate urls for UrlRewrite and save it in storage * * @param \Magento\Framework\Event\Observer $observer * @return void */ public function execute(\Magento\Framework\Event\Observer $observer) { foreach ($observer->getEvent()->getProducts() as $productId) { $product = $this->productRepository->getById($productId, false, $this->request->getParam('store_id', Store::DEFAULT_STORE_ID)); $this->urlPersist->deleteByData([UrlRewrite::ENTITY_ID => $product->getId(), UrlRewrite::ENTITY_TYPE => ProductUrlRewriteGenerator::ENTITY_TYPE]); $this->urlPersist->replace($this->productUrlRewriteGenerator->generate($product)); } }
/** * @return void */ public function execute() { $backUrl = $this->getRequest()->getParam(\Magento\Framework\App\Action\Action::PARAM_NAME_URL_ENCODED); $productId = (int) $this->getRequest()->getParam('product_id'); if (!$backUrl || !$productId) { $this->_redirect('/'); return; } try { $product = $this->productRepository->getById($productId); $model = $this->_objectManager->create('Magento\\ProductAlert\\Model\\Price')->setCustomerId($this->_customerSession->getCustomerId())->setProductId($product->getId())->setPrice($product->getFinalPrice())->setWebsiteId($this->_objectManager->get('Magento\\Store\\Model\\StoreManagerInterface')->getStore()->getWebsiteId()); $model->save(); $this->messageManager->addSuccess(__('You saved the alert subscription.')); } catch (NoSuchEntityException $noEntityException) { /* @var $product \Magento\Catalog\Model\Product */ $this->messageManager->addError(__('There are not enough parameters.')); if ($this->_isInternal($backUrl)) { $this->getResponse()->setRedirect($backUrl); } else { $this->_redirect('/'); } return; } catch (\Exception $e) { $this->messageManager->addException($e, __('Unable to update the alert subscription.')); } $this->getResponse()->setRedirect($this->_redirect->getRedirectUrl()); }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $this->appState->setAreaCode('catalog'); /** @var ProductCollection $productCollection */ $productCollection = $this->productCollectionFactory->create(); $productIds = $productCollection->getAllIds(); if (!count($productIds)) { $output->writeln("<info>No product images to resize</info>"); return; } try { foreach ($productIds as $productId) { try { /** @var Product $product */ $product = $this->productRepository->getById($productId); } catch (NoSuchEntityException $e) { continue; } /** @var ImageCache $imageCache */ $imageCache = $this->imageCacheFactory->create(); $imageCache->generate($product); $output->write("."); } } catch (\Exception $e) { $output->writeln("<error>{$e->getMessage()}</error>"); return; } $output->write("\n"); $output->writeln("<info>Product images resized successfully</info>"); }
/** * @return \Magento\Framework\Controller\Result\Redirect */ public function executeInternal() { $backUrl = $this->getRequest()->getParam(Action::PARAM_NAME_URL_ENCODED); $productId = (int) $this->getRequest()->getParam('product_id'); /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$backUrl || !$productId) { $resultRedirect->setPath('/'); return $resultRedirect; } try { /* @var $product \Magento\Catalog\Model\Product */ $product = $this->productRepository->getById($productId); /** @var \Magento\ProductAlert\Model\Stock $model */ $model = $this->_objectManager->create('Magento\\ProductAlert\\Model\\Stock')->setCustomerId($this->customerSession->getCustomerId())->setProductId($product->getId())->setWebsiteId($this->_objectManager->get('Magento\\Store\\Model\\StoreManagerInterface')->getStore()->getWebsiteId()); $model->save(); $this->messageManager->addSuccess(__('Alert subscription has been saved.')); } catch (NoSuchEntityException $noEntityException) { $this->messageManager->addError(__('There are not enough parameters.')); $resultRedirect->setUrl($backUrl); return $resultRedirect; } catch (\Exception $e) { $this->messageManager->addException($e, __('We can\'t update the alert subscription right now.')); } $resultRedirect->setUrl($this->_redirect->getRedirectUrl()); return $resultRedirect; }
/** * @return \Magento\Framework\Controller\Result\Redirect */ public function execute() { $productId = (int) $this->getRequest()->getParam('product'); /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$productId) { $resultRedirect->setPath('/'); return $resultRedirect; } try { $product = $this->productRepository->getById($productId); if (!$product->isVisibleInCatalog()) { throw new NoSuchEntityException(); } $model = $this->_objectManager->create('Magento\\ProductAlert\\Model\\Stock')->setCustomerId($this->customerSession->getCustomerId())->setProductId($product->getId())->setWebsiteId($this->_objectManager->get('Magento\\Store\\Model\\StoreManagerInterface')->getStore()->getWebsiteId())->loadByParam(); if ($model->getId()) { $model->delete(); } $this->messageManager->addSuccess(__('You will no longer receive stock alerts for this product.')); } catch (NoSuchEntityException $noEntityException) { $this->messageManager->addError(__('The product was not found.')); $resultRedirect->setPath('customer/account/'); return $resultRedirect; } catch (\Exception $e) { $this->messageManager->addException($e, __('Unable to update the alert subscription.')); } $resultRedirect->setUrl($product->getProductUrl()); return $resultRedirect; }
/** * {@inheritdoc} */ protected function execute(InputInterface $input, OutputInterface $output) { $this->appState->setAreaCode('catalog'); /** @var ProductCollection $productCollection */ $productCollection = $this->productCollectionFactory->create(); $productIds = $productCollection->getAllIds(); if (!count($productIds)) { $output->writeln("<info>No product images to resize</info>"); // we must have an exit code higher than zero to indicate something was wrong return \Magento\Framework\Console\Cli::RETURN_SUCCESS; } try { foreach ($productIds as $productId) { try { /** @var Product $product */ $product = $this->productRepository->getById($productId); } catch (NoSuchEntityException $e) { continue; } /** @var ImageCache $imageCache */ $imageCache = $this->imageCacheFactory->create(); $imageCache->generate($product); $output->write("."); } } catch (\Exception $e) { $output->writeln("<error>{$e->getMessage()}</error>"); // we must have an exit code higher than zero to indicate something was wrong return \Magento\Framework\Console\Cli::RETURN_FAILURE; } $output->write("\n"); $output->writeln("<info>Product images resized successfully</info>"); }
/** * @return void */ public function execute() { $productId = (int) $this->getRequest()->getParam('product'); if (!$productId) { $this->_redirect(''); return; } try { $product = $this->productRepository->getById($productId); if (!$product->isVisibleInCatalog()) { throw new NoSuchEntityException(); } $model = $this->_objectManager->create('Magento\\ProductAlert\\Model\\Price')->setCustomerId($this->_customerSession->getCustomerId())->setProductId($product->getId())->setWebsiteId($this->_objectManager->get('Magento\\Store\\Model\\StoreManagerInterface')->getStore()->getWebsiteId())->loadByParam(); if ($model->getId()) { $model->delete(); } $this->messageManager->addSuccess(__('You deleted the alert subscription.')); } catch (NoSuchEntityException $noEntityException) { /* @var $product \Magento\Catalog\Model\Product */ $this->messageManager->addError(__('We can\'t find the product.')); $this->_redirect('customer/account/'); return; } catch (\Exception $e) { $this->messageManager->addException($e, __('Unable to update the alert subscription.')); } $this->getResponse()->setRedirect($product->getProductUrl()); }
/** * @param int $prodId Magento ID for the product * @param array $categories Odoo IDs of the categories. */ public function replicateCategories($prodId, $categories) { /* get current categories links for the product */ $prod = $this->_mageRepoProd->getById($prodId); $sku = $prod->getSku(); $catsExist = $prod->getCategoryIds(); $catsFound = []; if (is_array($categories)) { foreach ($categories as $catOdooId) { $catMageId = $this->_repoRegistry->getCategoryMageIdByOdooId($catOdooId); if (!in_array($catMageId, $catsExist)) { /* create new product link if not exists */ /** @var CategoryProductLinkInterface $prodLink */ $prodLink = $this->_manObj->create(CategoryProductLinkInterface::class); $prodLink->setCategoryId($catMageId); $prodLink->setSku($sku); $prodLink->setPosition(1); $this->_mageRepoCatLink->save($prodLink); } /* register found link */ $catsFound[] = $catMageId; } } /* get difference between exist & found */ $diff = array_diff($catsExist, $catsFound); foreach ($diff as $catMageId) { $this->_mageRepoCatLink->deleteByIds($catMageId, $sku); } }
/** * Action to accept new configuration for a wishlist item * * @return \Magento\Framework\Controller\Result\Redirect */ public function executeInternal() { $productId = (int)$this->getRequest()->getParam('product'); /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$productId) { $resultRedirect->setPath('*/'); return $resultRedirect; } try { $product = $this->productRepository->getById($productId); } catch (NoSuchEntityException $e) { $product = null; } if (!$product || !$product->isVisibleInCatalog()) { $this->messageManager->addError(__('We can\'t specify a product.')); $resultRedirect->setPath('*/'); return $resultRedirect; } try { $id = (int)$this->getRequest()->getParam('id'); /* @var \Magento\Wishlist\Model\Item */ $item = $this->_objectManager->create('Magento\Wishlist\Model\Item'); $item->load($id); $wishlist = $this->wishlistProvider->getWishlist($item->getWishlistId()); if (!$wishlist) { $resultRedirect->setPath('*/'); return $resultRedirect; } $buyRequest = new \Magento\Framework\DataObject($this->getRequest()->getParams()); $wishlist->updateItem($id, $buyRequest)->save(); $this->_objectManager->get('Magento\Wishlist\Helper\Data')->calculate(); $this->_eventManager->dispatch( 'wishlist_update_item', ['wishlist' => $wishlist, 'product' => $product, 'item' => $wishlist->getItem($id)] ); $this->_objectManager->get('Magento\Wishlist\Helper\Data')->calculate(); $message = __('%1 has been updated in your Wish List.', $product->getName()); $this->messageManager->addSuccess($message); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addError(__('We can\'t update your Wish List right now.')); $this->_objectManager->get('Psr\Log\LoggerInterface')->critical($e); } $resultRedirect->setPath('*/*', ['wishlist_id' => $wishlist->getId()]); return $resultRedirect; }
/** * Adding new item * * @return \Magento\Framework\Controller\Result\Redirect * @throws NotFoundException * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public function execute() { /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$this->formKeyValidator->validate($this->getRequest())) { return $resultRedirect->setPath('*/'); } $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { throw new NotFoundException(__('Page not found.')); } $session = $this->_customerSession; $requestParams = $this->getRequest()->getParams(); if ($session->getBeforeWishlistRequest()) { $requestParams = $session->getBeforeWishlistRequest(); $session->unsBeforeWishlistRequest(); } $productId = isset($requestParams['product']) ? (int) $requestParams['product'] : null; if (!$productId) { $resultRedirect->setPath('*/'); return $resultRedirect; } try { $product = $this->productRepository->getById($productId); } catch (NoSuchEntityException $e) { $product = null; } if (!$product || !$product->isVisibleInCatalog()) { $this->messageManager->addErrorMessage(__('We can\'t specify a product.')); $resultRedirect->setPath('*/'); return $resultRedirect; } try { $buyRequest = new \Magento\Framework\DataObject($requestParams); $result = $wishlist->addNewItem($product, $buyRequest); if (is_string($result)) { throw new \Magento\Framework\Exception\LocalizedException(__($result)); } $wishlist->save(); $this->_eventManager->dispatch('wishlist_add_product', ['wishlist' => $wishlist, 'product' => $product, 'item' => $result]); $referer = $session->getBeforeWishlistUrl(); if ($referer) { $session->setBeforeWishlistUrl(null); } else { $referer = $this->_redirect->getRefererUrl(); } $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); $this->messageManager->addComplexSuccessMessage('addProductSuccessMessage', ['product_name' => $product->getName(), 'referer' => $referer]); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addErrorMessage(__('We can\'t add the item to Wish List right now: %1.', $e->getMessage())); } catch (\Exception $e) { $this->messageManager->addExceptionMessage($e, __('We can\'t add the item to Wish List right now.')); } $resultRedirect->setPath('*', ['wishlist_id' => $wishlist->getId()]); return $resultRedirect; }
/** * Adding new item * * @return \Magento\Framework\Controller\Result\Redirect * @throws NotFoundException * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.UnusedLocalVariable) */ public function execute() { $wishlist = $this->wishlistProvider->getWishlist(); if (!$wishlist) { throw new NotFoundException(__('Page not found.')); } $session = $this->_customerSession; $requestParams = $this->getRequest()->getParams(); if ($session->getBeforeWishlistRequest()) { $requestParams = $session->getBeforeWishlistRequest(); $session->unsBeforeWishlistRequest(); } $productId = isset($requestParams['product']) ? (int) $requestParams['product'] : null; /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); if (!$productId) { $resultRedirect->setPath('*/'); return $resultRedirect; } try { $product = $this->productRepository->getById($productId); } catch (NoSuchEntityException $e) { $product = null; } if (!$product || !$product->isVisibleInCatalog()) { $this->messageManager->addError(__('We can\'t specify a product.')); $resultRedirect->setPath('*/'); return $resultRedirect; } try { $buyRequest = new \Magento\Framework\Object($requestParams); $result = $wishlist->addNewItem($product, $buyRequest); if (is_string($result)) { throw new \Magento\Framework\Exception\LocalizedException(__($result)); } $wishlist->save(); $this->_eventManager->dispatch('wishlist_add_product', ['wishlist' => $wishlist, 'product' => $product, 'item' => $result]); $referer = $session->getBeforeWishlistUrl(); if ($referer) { $session->setBeforeWishlistUrl(null); } else { $referer = $this->_redirect->getRefererUrl(); } $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); $message = __('%1 has been added to your wishlist. Click <a href="%2">here</a> to continue shopping.', $this->_objectManager->get('Magento\\Framework\\Escaper')->escapeHtml($product->getName()), $this->_objectManager->get('Magento\\Framework\\Escaper')->escapeUrl($referer)); $this->messageManager->addSuccess($message); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError(__('An error occurred while adding item to wish list: %1', $e->getMessage())); } catch (\Exception $e) { $this->messageManager->addError(__('An error occurred while adding item to wish list.')); $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e); } $resultRedirect->setPath('*', ['wishlist_id' => $wishlist->getId()]); return $resultRedirect; }
/** * Initialize product instance from request data * * @return \Magento\Catalog\Model\Product || false */ protected function _initProduct() { $productId = (int) $this->getRequest()->getParam('product'); if ($productId) { $storeId = $this->_objectManager->get('Magento\\Store\\Model\\StoreManagerInterface')->getStore()->getId(); try { return $this->productRepository->getById($productId, false, $storeId); } catch (NoSuchEntityException $e) { return false; } } return false; }
/** * @return void */ public function execute() { $response = new \Magento\Framework\Object(); $id = $this->getRequest()->getParam('id'); if (intval($id) > 0) { $product = $this->productRepository->getById($id); $response->setId($id); $response->addData($product->getData()); $response->setError(0); } else { $response->setError(1); $response->setMessage(__('We can\'t get the product ID.')); } $this->getResponse()->representJson($response->toJSON()); }
/** * Update data for configurable product configurations * * @param \Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject * @param \Magento\Catalog\Model\Product $configurableProduct * * @return \Magento\Catalog\Model\Product * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterInitialize(\Magento\Catalog\Controller\Adminhtml\Product\Initialization\Helper $subject, \Magento\Catalog\Model\Product $configurableProduct) { $configurations = $this->request->getParam('configurations', []); $configurations = $this->variationHandler->duplicateImagesForVariations($configurations); foreach ($configurations as $productId => $productData) { /** @var \Magento\Catalog\Model\Product $product */ $product = $this->productRepository->getById($productId, false, $this->request->getParam('store', 0)); $productData = $this->variationHandler->processMediaGallery($product, $productData); $product->addData($productData); if ($product->hasDataChanges()) { $product->save(); } } return $configurableProduct; }
/** * @param ImportProduct $import * @param bool $result * @return bool */ public function afterImportData(ImportProduct $import, $result) { if ($import->getAffectedEntityIds()) { foreach ($import->getAffectedEntityIds() as $productId) { $product = $this->productRepository->getById($productId); $productUrls = $this->productUrlRewriteGenerator->generate($product); if ($productUrls) { $this->urlPersist->replace($productUrls); } } } elseif (ImportExport::BEHAVIOR_DELETE == $import->getBehavior()) { $this->clearProductUrls($import); } return $result; }
/** * Prepares and render result of composite product configuration request * * The $configureResult variable holds either: * - 'ok' = true, and 'product_id', 'buy_request', 'current_store_id', 'current_customer_id' * - 'error' = true, and 'message' to show * * @param \Magento\Framework\DataObject $configureResult * @return \Magento\Framework\View\Result\Layout */ public function renderConfigureResult(\Magento\Framework\DataObject $configureResult) { try { if (!$configureResult->getOk()) { throw new \Magento\Framework\Exception\LocalizedException(__($configureResult->getMessage())); } $currentStoreId = (int) $configureResult->getCurrentStoreId(); if (!$currentStoreId) { $currentStoreId = $this->_storeManager->getStore()->getId(); } $product = $this->productRepository->getById($configureResult->getProductId(), false, $currentStoreId); $this->_coreRegistry->register('current_product', $product); $this->_coreRegistry->register('product', $product); // Register customer we're working with $customerId = (int) $configureResult->getCurrentCustomerId(); $this->_coreRegistry->register(RegistryConstants::CURRENT_CUSTOMER_ID, $customerId); // Prepare buy request values $buyRequest = $configureResult->getBuyRequest(); if ($buyRequest) { $this->_catalogProduct->prepareProductOptions($product, $buyRequest); } $isOk = true; $productType = $product->getTypeId(); } catch (\Exception $e) { $isOk = false; $productType = null; $this->_coreRegistry->register('composite_configure_result_error_message', $e->getMessage()); } return $this->_initConfigureResultLayout($isOk, $productType); }
/** * Get product data * * @return Product */ public function getProductData() { if ($this->getReviewId() && !$this->getProductCacheData()) { $product = $this->productRepository->getById($this->getReviewData()->getEntityPkValue()); $this->setProductCacheData($product); } return $this->getProductCacheData(); }
/** * Product Getter. Load product if not exist. * * @return CatalogModelProduct */ public function getProduct() { if ($this->getData('product') === null && $this->getProductId() !== null) { $product = $this->productRepository->getById($this->getProductId(), false, $this->getStoreId()); $this->setData('product', $product); } return $this->getData('product'); }
/** * Get option product * * @return Product */ public function getProduct() { //In some cases product_id is present instead product instance if (null === $this->_product && $this->getProductId()) { $this->_product = $this->productRepository->getById($this->getProductId()); } return $this->_product; }
/** * Retrieve current product model * * @return \Magento\Catalog\Model\Product */ public function getProduct() { if (!$this->_coreRegistry->registry('product') && $this->getProductId()) { $product = $this->productRepository->getById($this->getProductId()); $this->_coreRegistry->register('product', $product); } return $this->_coreRegistry->registry('product'); }
/** * Initialize grouped product links * * @param \Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks $subject * @param \Magento\Catalog\Model\Product $product * @param array $links * * @return \Magento\Catalog\Model\Product * @SuppressWarnings(PHPMD.UnusedFormalParameter) * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function beforeInitializeLinks(\Magento\Catalog\Model\Product\Initialization\Helper\ProductLinks $subject, \Magento\Catalog\Model\Product $product, array $links) { if ($product->getTypeId() === TypeGrouped::TYPE_CODE && !$product->getGroupedReadonly()) { $links = isset($links[self::TYPE_NAME]) ? $links[self::TYPE_NAME] : $product->getGroupedLinkData(); if (!is_array($links)) { $links = []; } if ($product->getGroupedLinkData()) { $links = array_merge($links, $product->getGroupedLinkData()); } $newLinks = []; $existingLinks = $product->getProductLinks(); foreach ($links as $linkRaw) { /** @var \Magento\Catalog\Api\Data\ProductLinkInterface $productLink */ $productLink = $this->productLinkFactory->create(); if (!isset($linkRaw['id'])) { continue; } $productId = $linkRaw['id']; if (!isset($linkRaw['qty'])) { $linkRaw['qty'] = 0; } $linkedProduct = $this->productRepository->getById($productId); $productLink->setSku($product->getSku())->setLinkType(self::TYPE_NAME)->setLinkedProductSku($linkedProduct->getSku())->setLinkedProductType($linkedProduct->getTypeId())->setPosition($linkRaw['position'])->getExtensionAttributes()->setQty($linkRaw['qty']); if (isset($linkRaw['custom_attributes'])) { $productLinkExtension = $productLink->getExtensionAttributes(); if ($productLinkExtension === null) { $productLinkExtension = $this->productLinkExtensionFactory->create(); } foreach ($linkRaw['custom_attributes'] as $option) { $name = $option['attribute_code']; $value = $option['value']; $setterName = 'set' . ucfirst($name); // Check if setter exists if (method_exists($productLinkExtension, $setterName)) { call_user_func([$productLinkExtension, $setterName], $value); } } $productLink->setExtensionAttributes($productLinkExtension); } $newLinks[] = $productLink; } $existingLinks = $this->removeUnExistingLinks($existingLinks, $newLinks); $product->setProductLinks(array_merge($existingLinks, $newLinks)); } }
/** * Product Getter. Load product if not exist. * * @return CatalogModelProduct */ public function getProduct() { if (is_null($this->getData('product')) && !is_null($this->getProductId())) { $product = $this->productRepository->getById($this->getProductId(), false, $this->getStoreId()); $this->setData('product', $product); } return $this->getData('product'); }
/** * Retrieve product instance by id * * @param int $id * @return ProductInterface * @throws InputException */ private function getProductById($id) { $product = $this->productRepository->getById($id); if (\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE !== $product->getTypeId()) { throw new InputException(__('Only implemented for configurable product: %1', $id)); } return $product; }
/** * Process stock emails * * @param \Magento\ProductAlert\Model\Email $email * @return $this * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ protected function _processStock(\Magento\ProductAlert\Model\Email $email) { $email->setType('stock'); foreach ($this->_getWebsites() as $website) { /* @var $website \Magento\Store\Model\Website */ if (!$website->getDefaultGroup() || !$website->getDefaultGroup()->getDefaultStore()) { continue; } if (!$this->_scopeConfig->getValue(self::XML_PATH_STOCK_ALLOW, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $website->getDefaultGroup()->getDefaultStore()->getId())) { continue; } try { $collection = $this->_stockColFactory->create()->addWebsiteFilter($website->getId())->addStatusFilter(0)->setCustomerOrder(); } catch (\Exception $e) { $this->_errors[] = $e->getMessage(); return $this; } $previousCustomer = null; $email->setWebsite($website); foreach ($collection as $alert) { try { if (!$previousCustomer || $previousCustomer->getId() != $alert->getCustomerId()) { $customer = $this->customerRepository->getById($alert->getCustomerId()); if ($previousCustomer) { $email->send(); } if (!$customer) { continue; } $previousCustomer = $customer; $email->clean(); $email->setCustomerData($customer); } else { $customer = $previousCustomer; } $product = $this->productRepository->getById($alert->getProductId(), false, $website->getDefaultStore()->getId()); $product->setCustomerGroupId($customer->getGroupId()); if ($product->isSalable()) { $email->addStockProduct($product); $alert->setSendDate($this->_dateFactory->create()->gmtDate()); $alert->setSendCount($alert->getSendCount() + 1); $alert->setStatus(1); $alert->save(); } } catch (\Exception $e) { $this->_errors[] = $e->getMessage(); } } if ($previousCustomer) { try { $email->send(); } catch (\Exception $e) { $this->_errors[] = $e->getMessage(); } } } return $this; }
/** * @return \Magento\Framework\Controller\Result\Json */ public function execute() { $response = new Object(); $id = $this->getRequest()->getParam('id'); if (intval($id) > 0) { $product = $this->productRepository->getById($id); $response->setId($id); $response->addData($product->getData()); $response->setError(0); } else { $response->setError(1); $response->setMessage(__('We can\'t retrieve the product ID.')); } /** @var \Magento\Framework\Controller\Result\Json $resultJson */ $resultJson = $this->resultFactory->create(ResultFactory::TYPE_JSON); $resultJson->setData($response->toArray()); return $resultJson; }
/** * Select one of the options and "prepare for cart" with a proper buy request * * @return ProductInterface */ protected function _prepareForCart() { $product = $this->productRepository->getById(1, true); $attributes = $this->model->getConfigurableAttributesAsArray($product); $attribute = reset($attributes); $optionValueId = $attribute['values'][0]['value_index']; $buyRequest = new \Magento\Framework\DataObject(['qty' => 5, 'super_attribute' => [$attribute['attribute_id'] => $optionValueId]]); $this->model->prepareForCart($buyRequest, $product); return $product; }
/** * Retrieve product * * @return ProductInterface|null */ protected function getProduct() { if (null !== $this->product) { return $this->product; } if (!($id = $this->request->getParam('current_product_id'))) { return null; } return $this->product = $this->productRepository->getById($id); }
/** * Action to accept new configuration for a wishlist item * * @return void */ public function execute() { $productId = (int) $this->getRequest()->getParam('product'); if (!$productId) { $this->_redirect('*/'); return; } try { $product = $this->productRepository->getById($productId); } catch (NoSuchEntityException $e) { $product = null; } if (!$product || !$product->isVisibleInCatalog()) { $this->messageManager->addError(__('We can\'t specify a product.')); $this->_redirect('*/'); return; } try { $id = (int) $this->getRequest()->getParam('id'); /* @var \Magento\Wishlist\Model\Item */ $item = $this->_objectManager->create('Magento\\Wishlist\\Model\\Item'); $item->load($id); $wishlist = $this->wishlistProvider->getWishlist($item->getWishlistId()); if (!$wishlist) { $this->_redirect('*/'); return; } $buyRequest = new \Magento\Framework\Object($this->getRequest()->getParams()); $wishlist->updateItem($id, $buyRequest)->save(); $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); $this->_eventManager->dispatch('wishlist_update_item', ['wishlist' => $wishlist, 'product' => $product, 'item' => $wishlist->getItem($id)]); $this->_objectManager->get('Magento\\Wishlist\\Helper\\Data')->calculate(); $message = __('%1 has been updated in your wish list.', $product->getName()); $this->messageManager->addSuccess($message); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addError(__('An error occurred while updating wish list.')); $this->_objectManager->get('Psr\\Log\\LoggerInterface')->critical($e); } $this->_redirect('*/*', ['wishlist_id' => $wishlist->getId()]); }
/** * @param ModelProduct $product * @return array */ private function getGalleryImages(ModelProduct $product) { //TODO: remove after fix MAGETWO-48040 $product = $this->productRepository->getById($product->getId()); $result = []; $mediaGallery = $product->getMediaGalleryImages(); foreach ($mediaGallery as $media) { $result[$media->getData('value_id')] = $this->getAllSizeImages($product, $media->getData('file')); } return $result; }
/** * Inits product to be used for product controller actions and layouts * $params can have following data: * 'category_id' - id of category to check and append to product as current. * If empty (except FALSE) - will be guessed (e.g. from last visited) to load as current. * * @param int $productId * @param \Magento\Framework\App\Action\Action $controller * @param \Magento\Framework\DataObject $params * * @return false|ModelProduct * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function initProduct($productId, $controller, $params = null) { // Prepare data for routine if (!$params) { $params = new \Magento\Framework\DataObject(); } // Init and load product $this->_eventManager->dispatch('catalog_controller_product_init_before', ['controller_action' => $controller, 'params' => $params]); if (!$productId) { return false; } try { $product = $this->productRepository->getById($productId, false, $this->_storeManager->getStore()->getId()); } catch (NoSuchEntityException $e) { return false; } if (!$this->canShow($product)) { return false; } if (!in_array($this->_storeManager->getStore()->getWebsiteId(), $product->getWebsiteIds())) { return false; } // Load product current category $categoryId = $params->getCategoryId(); if (!$categoryId && $categoryId !== false) { $lastId = $this->_catalogSession->getLastVisitedCategoryId(); if ($product->canBeShowInCategory($lastId)) { $categoryId = $lastId; } } elseif (!$product->canBeShowInCategory($categoryId)) { $categoryId = null; } if ($categoryId) { try { $category = $this->categoryRepository->get($categoryId); } catch (NoSuchEntityException $e) { $category = null; } if ($category) { $product->setCategory($category); $this->_coreRegistry->register('current_category', $category); } } // Register current data and dispatch final events $this->_coreRegistry->register('current_product', $product); $this->_coreRegistry->register('product', $product); try { $this->_eventManager->dispatch('catalog_controller_product_init_after', ['product' => $product, 'controller_action' => $controller]); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->_logger->critical($e); return false; } return $product; }