当前位置: 首页>>代码示例>>PHP>>正文


PHP ProductRepositoryInterface::getById方法代码示例

本文整理汇总了PHP中Magento\Catalog\Api\ProductRepositoryInterface::getById方法的典型用法代码示例。如果您正苦于以下问题:PHP ProductRepositoryInterface::getById方法的具体用法?PHP ProductRepositoryInterface::getById怎么用?PHP ProductRepositoryInterface::getById使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Magento\Catalog\Api\ProductRepositoryInterface的用法示例。


在下文中一共展示了ProductRepositoryInterface::getById方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: execute

 /**
  * @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());
 }
开发者ID:shabbirvividads,项目名称:magento2,代码行数:30,代码来源:Price.php

示例2: execute

 /**
  * {@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>");
 }
开发者ID:kidaa30,项目名称:magento2-platformsh,代码行数:33,代码来源:ImagesResizeCommand.php

示例3: executeInternal

 /**
  * @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;
 }
开发者ID:nblair,项目名称:magescotch,代码行数:30,代码来源:Stock.php

示例4: execute

 /**
  * {@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>");
 }
开发者ID:Doability,项目名称:magento2dev,代码行数:35,代码来源:ImagesResizeCommand.php

示例5: execute

 /**
  * @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;
 }
开发者ID:kid17,项目名称:magento2,代码行数:32,代码来源:Stock.php

示例6: replicateCategories

 /**
  * @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);
     }
 }
开发者ID:praxigento,项目名称:mobi_mod_mage2_odoo,代码行数:33,代码来源:Category.php

示例7: execute

 /**
  * 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));
     }
 }
开发者ID:CompassPointMedia,项目名称:magento2,代码行数:14,代码来源:ProductToWebsiteChangeObserver.php

示例8: executeInternal

    /**
     * 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;
    }
开发者ID:nblair,项目名称:magescotch,代码行数:61,代码来源:UpdateItemOptions.php

示例9: execute

 /**
  * 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;
 }
开发者ID:Doability,项目名称:magento2dev,代码行数:65,代码来源:Add.php

示例10: execute

 /**
  * 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;
 }
开发者ID:opexsw,项目名称:magento2,代码行数:64,代码来源:Add.php

示例11: _initProduct

 /**
  * 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;
 }
开发者ID:kid17,项目名称:magento2,代码行数:18,代码来源:Add.php

示例12: execute

 /**
  * @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());
 }
开发者ID:shabbirvividads,项目名称:magento2,代码行数:18,代码来源:JsonProductInfo.php

示例13: afterInitialize

 /**
  * 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;
 }
开发者ID:pradeep-wagento,项目名称:magento2,代码行数:24,代码来源:UpdateConfigurations.php

示例14: afterImportData

 /**
  * @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;
 }
开发者ID:shabbirvividads,项目名称:magento2,代码行数:20,代码来源:Import.php

示例15: renderConfigureResult

 /**
  * 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);
 }
开发者ID:kidaa30,项目名称:magento2-platformsh,代码行数:40,代码来源:Composite.php


注:本文中的Magento\Catalog\Api\ProductRepositoryInterface::getById方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。