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


PHP ProductFactory::create方法代码示例

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


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

示例1: getLoadedProductCollection

 /**
  * Products collection.
  *
  * @return array
  */
 public function getLoadedProductCollection()
 {
     $productsToDisplay = [];
     $mode = $this->getRequest()->getActionName();
     $customerId = $this->getRequest()->getParam('customer_id');
     $limit = $this->recommnededHelper->getDisplayLimitByMode($mode);
     //login customer to receive the recent products
     $session = $this->sessionFactory->create();
     $isLoggedIn = $session->loginById($customerId);
     $collection = $this->viewed;
     $productItems = $collection->getItemsCollection()->setPageSize($limit);
     //get the product ids from items collection
     $productIds = $productItems->getColumnValues('product_id');
     //get product collection to check for salable
     $productCollection = $this->productFactory->create()->getCollection()->addAttributeToSelect('*')->addFieldToFilter('entity_id', ['in' => $productIds]);
     //show products only if is salable
     foreach ($productCollection as $product) {
         if ($product->isSalable()) {
             $productsToDisplay[$product->getId()] = $product;
         }
     }
     $this->helper->log('Recentlyviewed customer  : ' . $customerId . ', mode ' . $mode . ', limit : ' . $limit . ', items found : ' . count($productItems) . ', is customer logged in : ' . $isLoggedIn . ', products :' . count($productsToDisplay));
     $session->logout();
     return $productsToDisplay;
 }
开发者ID:dotmailer,项目名称:dotmailer-magento2-extension,代码行数:30,代码来源:Recentlyviewed.php

示例2: copy

 /**
  * Create product duplicate
  *
  * @param \Magento\Catalog\Model\Product $product
  * @return \Magento\Catalog\Model\Product
  */
 public function copy(\Magento\Catalog\Model\Product $product)
 {
     $product->getWebsiteIds();
     $product->getCategoryIds();
     /** @var \Magento\Catalog\Model\Product $duplicate */
     $duplicate = $this->productFactory->create();
     $duplicate->setData($product->getData());
     $duplicate->setOptions([]);
     $duplicate->setIsDuplicate(true);
     $duplicate->setOriginalId($product->getEntityId());
     $duplicate->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
     $duplicate->setCreatedAt(null);
     $duplicate->setUpdatedAt(null);
     $duplicate->setId(null);
     $duplicate->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
     $this->copyConstructor->build($product, $duplicate);
     $isDuplicateSaved = false;
     do {
         $urlKey = $duplicate->getUrlKey();
         $urlKey = preg_match('/(.*)-(\\d+)$/', $urlKey, $matches) ? $matches[1] . '-' . ($matches[2] + 1) : $urlKey . '-1';
         $duplicate->setUrlKey($urlKey);
         try {
             $duplicate->save();
             $isDuplicateSaved = true;
         } catch (\Magento\Framework\Exception\AlreadyExistsException $e) {
         }
     } while (!$isDuplicateSaved);
     $this->getOptionRepository()->duplicate($product, $duplicate);
     $metadata = $this->getMetadataPool()->getMetadata(ProductInterface::class);
     $product->getResource()->duplicate($product->getData($metadata->getLinkField()), $duplicate->getData($metadata->getLinkField()));
     return $duplicate;
 }
开发者ID:Doability,项目名称:magento2dev,代码行数:38,代码来源:Copier.php

示例3: _toHtml

 /**
  * @return string
  */
 protected function _toHtml()
 {
     $storeId = $this->_getStoreId();
     $storeModel = $this->_storeManager->getStore($storeId);
     $newUrl = $this->_urlBuilder->getUrl('rss/catalog/new/store_id/' . $storeId);
     $title = __('New Products from %1', $storeModel->getFrontendName());
     $lang = $this->_scopeConfig->getValue('general/locale/code', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeModel);
     /** @var $rssObj \Magento\Rss\Model\Rss */
     $rssObj = $this->_rssFactory->create();
     $rssObj->_addHeader(array('title' => $title, 'description' => $title, 'link' => $newUrl, 'charset' => 'UTF-8', 'language' => $lang));
     /** @var $product \Magento\Catalog\Model\Product */
     $product = $this->_productFactory->create();
     $todayStartOfDayDate = $this->_localeDate->date()->setTime('00:00:00')->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT);
     $todayEndOfDayDate = $this->_localeDate->date()->setTime('23:59:59')->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT);
     /** @var $products \Magento\Catalog\Model\Resource\Product\Collection */
     $products = $product->getCollection();
     $products->setStoreId($storeId);
     $products->addStoreFilter()->addAttributeToFilter('news_from_date', array('or' => array(0 => array('date' => true, 'to' => $todayEndOfDayDate), 1 => array('is' => new \Zend_Db_Expr('null')))), 'left')->addAttributeToFilter('news_to_date', array('or' => array(0 => array('date' => true, 'from' => $todayStartOfDayDate), 1 => array('is' => new \Zend_Db_Expr('null')))), 'left')->addAttributeToFilter(array(array('attribute' => 'news_from_date', 'is' => new \Zend_Db_Expr('not null')), array('attribute' => 'news_to_date', 'is' => new \Zend_Db_Expr('not null'))))->addAttributeToSort('news_from_date', 'desc')->addAttributeToSelect(array('name', 'short_description', 'description'), 'inner')->addAttributeToSelect(array('price', 'special_price', 'special_from_date', 'special_to_date', 'msrp_enabled', 'msrp_display_actual_price_type', 'msrp', 'thumbnail'), 'left')->applyFrontendPriceLimitations();
     $products->setVisibility($this->_visibility->getVisibleInCatalogIds());
     /*
     using resource iterator to load the data one by one
     instead of loading all at the same time. loading all data at the same time can cause the big memory allocation.
     */
     $this->_resourceIterator->walk($products->getSelect(), array(array($this, 'addNewItemXmlCallback')), array('rssObj' => $rssObj, 'product' => $product));
     return $rssObj->createRssXml();
 }
开发者ID:aiesh,项目名称:magento2,代码行数:29,代码来源:NewCatalog.php

示例4: getTreeArray

 /**
  * Get categories tree as recursive array
  *
  * @param int $parentId
  * @param bool $asJson
  * @param int $recursionLevel
  * @return array
  */
 public function getTreeArray($parentId = null, $asJson = false, $recursionLevel = 3)
 {
     $productId = $this->_request->getParam('product');
     if ($productId) {
         $product = $this->_productFactory->create()->setId($productId);
         $this->_allowedCategoryIds = $product->getCategoryIds();
         unset($product);
     }
     $result = [];
     if ($parentId) {
         try {
             $category = $this->categoryRepository->get($parentId);
         } catch (NoSuchEntityException $e) {
             $category = null;
         }
         if ($category) {
             $tree = $this->_getNodesArray($this->getNode($category, $recursionLevel));
             if (!empty($tree) && !empty($tree['children'])) {
                 $result = $tree['children'];
             }
         }
     } else {
         $result = $this->_getNodesArray($this->getRoot(null, $recursionLevel));
     }
     if ($asJson) {
         return $this->_jsonEncoder->encode($result);
     }
     $this->_allowedCategoryIds = [];
     return $result;
 }
开发者ID:pradeep-wagento,项目名称:magento2,代码行数:38,代码来源:Tree.php

示例5: build

 /**
  * Build product based on user request
  *
  * @param RequestInterface $request
  * @return \Magento\Catalog\Model\Product
  */
 public function build(RequestInterface $request)
 {
     $productId = (int) $request->getParam('id');
     /** @var $product \Magento\Catalog\Model\Product */
     $product = $this->productFactory->create();
     $product->setStoreId($request->getParam('store', 0));
     $typeId = $request->getParam('type');
     if (!$productId && $typeId) {
         $product->setTypeId($typeId);
     }
     $product->setData('_edit_mode', true);
     if ($productId) {
         try {
             $product->load($productId);
         } catch (\Exception $e) {
             $product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE);
             $this->logger->critical($e);
         }
     }
     $setId = (int) $request->getParam('set');
     if ($setId) {
         $product->setAttributeSetId($setId);
     }
     $this->registry->register('product', $product);
     $this->registry->register('current_product', $product);
     $this->wysiwygConfig->setStoreId($request->getParam('store'));
     return $product;
 }
开发者ID:kidaa30,项目名称:magento2-platformsh,代码行数:34,代码来源:Builder.php

示例6: _validateProductVariations

 /**
  * Product variations attributes validation
  *
  * @param Product $parentProduct
  * @param array $products
  * @param RequestInterface $request
  * @return array
  */
 protected function _validateProductVariations(Product $parentProduct, array $products, RequestInterface $request)
 {
     $this->eventManager->dispatch('catalog_product_validate_variations_before', ['product' => $parentProduct, 'variations' => $products]);
     $validationResult = [];
     foreach ($products as $productData) {
         $product = $this->productFactory->create();
         $product->setData('_edit_mode', true);
         $storeId = $request->getParam('store');
         if ($storeId) {
             $product->setStoreId($storeId);
         }
         $product->setAttributeSetId($parentProduct->getAttributeSetId());
         $product->addData($this->getRequiredDataFromProduct($parentProduct));
         $product->addData($productData);
         $product->setCollectExceptionMessages(true);
         $configurableAttribute = [];
         $encodedData = $productData['configurable_attribute'];
         if ($encodedData) {
             $configurableAttribute = $this->jsonHelper->jsonDecode($encodedData);
         }
         $configurableAttribute = implode('-', $configurableAttribute);
         $errorAttributes = $product->validate();
         if (is_array($errorAttributes)) {
             foreach ($errorAttributes as $attributeCode => $result) {
                 if (is_string($result)) {
                     $key = 'variations-matrix-' . $configurableAttribute . '-' . $attributeCode;
                     $validationResult[$key] = $result;
                 }
             }
         }
     }
     return $validationResult;
 }
开发者ID:tingyeeh,项目名称:magento2,代码行数:41,代码来源:Plugin.php

示例7: execute

 /**
  * Get associated grouped products grid popup
  *
  * @return \Magento\Framework\View\Result\Layout
  */
 public function execute()
 {
     $productId = (int) $this->getRequest()->getParam('id');
     /** @var $product \Magento\Catalog\Model\Product */
     $product = $this->factory->create();
     $product->setStoreId($this->getRequest()->getParam('store', 0));
     $typeId = $this->getRequest()->getParam('type');
     if (!$productId && $typeId) {
         $product->setTypeId($typeId);
     }
     $product->setData('_edit_mode', true);
     if ($productId) {
         try {
             $product->load($productId);
         } catch (\Exception $e) {
             $product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE);
             $this->logger->critical($e);
         }
     }
     $setId = (int) $this->getRequest()->getParam('set');
     if ($setId) {
         $product->setAttributeSetId($setId);
     }
     $this->registry->register('current_product', $product);
     /** @var \Magento\Framework\View\Result\Layout $resultLayout */
     $resultLayout = $this->resultFactory->create(ResultFactory::TYPE_LAYOUT);
     return $resultLayout;
 }
开发者ID:kidaa30,项目名称:magento2-platformsh,代码行数:33,代码来源:Popup.php

示例8: run

 /**
  * {@inheritdoc}
  */
 public function run()
 {
     $this->logger->log('Installing product links:');
     $entityFileAssociation = ['related', 'upsell', 'crosssell'];
     foreach ($this->postInstaller->getInstalledModuleList() as $moduleName) {
         foreach ($entityFileAssociation as $linkType) {
             $fileName = substr($moduleName, strpos($moduleName, "_") + 1) . '/Links/' . $linkType . '.csv';
             $fileName = $this->fixtureHelper->getPath($fileName);
             if (!$fileName) {
                 continue;
             }
             /** @var \Magento\SampleData\Helper\Csv\ReaderFactory $csvReader */
             $csvReader = $this->csvReaderFactory->create(['fileName' => $fileName, 'mode' => 'r']);
             foreach ($csvReader as $row) {
                 /** @var \Magento\Catalog\Model\Product $product */
                 $product = $this->productFactory->create();
                 $productId = $product->getIdBySku($row['sku']);
                 if (!$productId) {
                     continue;
                 }
                 $product->setId($productId);
                 $links = [$linkType => []];
                 foreach (explode("\n", $row['linked_sku']) as $linkedProductSku) {
                     $linkedProductId = $product->getIdBySku($linkedProductSku);
                     if ($linkedProductId) {
                         $links[$linkType][$linkedProductId] = [];
                     }
                 }
                 $this->linksInitializer->initializeLinks($product, $links);
                 $product->getLinkInstance()->saveProductRelations($product);
                 $this->logger->logInline('.');
             }
         }
     }
 }
开发者ID:ktplKunj,项目名称:TestMagento,代码行数:38,代码来源:ProductLink.php

示例9: _getProduct

 /**
  * Get or create new instance of product
  *
  * @return \Magento\Catalog\Model\Product
  */
 private function _getProduct()
 {
     if (!$this->hasData('product')) {
         $this->setProduct($this->_productFactory->create());
     }
     return $this->getProduct();
 }
开发者ID:kidaa30,项目名称:magento2-platformsh,代码行数:12,代码来源:Edit.php

示例10: copy

 /**
  * Create product duplicate
  *
  * @param \Magento\Catalog\Model\Product $product
  * @return \Magento\Catalog\Model\Product
  */
 public function copy(\Magento\Catalog\Model\Product $product)
 {
     $product->getWebsiteIds();
     $product->getCategoryIds();
     $duplicate = $this->productFactory->create();
     $duplicate->setData($product->getData());
     $duplicate->setIsDuplicate(true);
     $duplicate->setOriginalId($product->getId());
     $duplicate->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
     $duplicate->setCreatedAt(null);
     $duplicate->setUpdatedAt(null);
     $duplicate->setId(null);
     $duplicate->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
     $this->copyConstructor->build($product, $duplicate);
     $isDuplicateSaved = false;
     do {
         $urlKey = $duplicate->getUrlKey();
         $urlKey = preg_match('/(.*)-(\\d+)$/', $urlKey, $matches) ? $matches[1] . '-' . ($matches[2] + 1) : $urlKey . '-1';
         $duplicate->setUrlKey($urlKey);
         try {
             $duplicate->save();
             $isDuplicateSaved = true;
         } catch (DuplicateEntryException $e) {
         }
     } while (!$isDuplicateSaved);
     $product->getOptionInstance()->duplicate($product->getId(), $duplicate->getId());
     $product->getResource()->duplicate($product->getId(), $duplicate->getId());
     return $duplicate;
 }
开发者ID:shabbirvividads,项目名称:magento2,代码行数:35,代码来源:Copier.php

示例11: create

 /**
  * Populate product with variation of attributes
  *
  * @param \Magento\Catalog\Api\Data\ProductInterface $product
  * @param array $attributes
  * @return \Magento\Catalog\Api\Data\ProductInterface[]
  */
 public function create(\Magento\Catalog\Api\Data\ProductInterface $product, $attributes)
 {
     $variations = $this->variationMatrix->getVariations($attributes);
     $products = [];
     foreach ($variations as $variation) {
         $price = $product->getPrice();
         /** @var \Magento\Catalog\Model\Product $item */
         $item = $this->productFactory->create();
         $item->setData($product->getData());
         $suffix = '';
         foreach ($variation as $attributeId => $valueInfo) {
             $suffix .= '-' . $valueInfo['value'];
             $customAttribute = $this->customAttributeFactory->create()->setAttributeCode($attributes[$attributeId]['attribute_code'])->setValue($valueInfo['value']);
             $customAttributes = array_merge($item->getCustomAttributes(), [$attributes[$attributeId]['attribute_code'] => $customAttribute]);
             $item->setData('custom_attributes', $customAttributes);
             $priceInfo = $valueInfo['price'];
             $price += (!empty($priceInfo['is_percent']) ? $product->getPrice() / 100.0 : 1.0) * $priceInfo['pricing_value'];
         }
         $item->setPrice($price);
         $item->setName($product->getName() . $suffix);
         $item->setSku($product->getSku() . $suffix);
         $item->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE);
         $products[] = $item;
     }
     return $products;
 }
开发者ID:shabbirvividads,项目名称:magento2,代码行数:33,代码来源:ProductVariationsBuilder.php

示例12: execute

 /**
  * Get associated grouped products grid popup
  *
  * @return void
  */
 public function execute()
 {
     $productId = (int) $this->getRequest()->getParam('id');
     /** @var $product \Magento\Catalog\Model\Product */
     $product = $this->factory->create();
     $product->setStoreId($this->getRequest()->getParam('store', 0));
     $typeId = $this->getRequest()->getParam('type');
     if (!$productId && $typeId) {
         $product->setTypeId($typeId);
     }
     $product->setData('_edit_mode', true);
     if ($productId) {
         try {
             $product->load($productId);
         } catch (\Exception $e) {
             $product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE);
             $this->logger->logException($e);
         }
     }
     $setId = (int) $this->getRequest()->getParam('set');
     if ($setId) {
         $product->setAttributeSetId($setId);
     }
     $this->registry->register('current_product', $product);
     $this->_view->loadLayout(false);
     $this->_view->renderLayout();
 }
开发者ID:aiesh,项目名称:magento2,代码行数:32,代码来源:Popup.php

示例13: getMediaAttributes

 /**
  * @return array
  */
 public function getMediaAttributes()
 {
     static $simple;
     if (empty($simple)) {
         $simple = $this->productFactory->create()->setTypeId(Type::TYPE_SIMPLE)->getMediaAttributes();
     }
     return $simple;
 }
开发者ID:Doability,项目名称:magento2dev,代码行数:11,代码来源:Bulk.php

示例14: getProductsCollection

 /**
  * @param int $storeId
  * @param int $customerGroupId
  * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
  */
 public function getProductsCollection($storeId, $customerGroupId)
 {
     $websiteId = $this->storeManager->getStore($storeId)->getWebsiteId();
     /** @var $product \Magento\Catalog\Model\Product */
     $product = $this->productFactory->create();
     $product->setStoreId($storeId);
     $collection = $product->getResourceCollection()->addPriceDataFieldFilter('%s < %s', ['final_price', 'price'])->addPriceData($customerGroupId, $websiteId)->addAttributeToSelect(['name', 'short_description', 'description', 'price', 'thumbnail', 'special_price', 'special_to_date', 'msrp_display_actual_price_type', 'msrp'], 'left')->addAttributeToSort('name', 'asc');
     return $collection;
 }
开发者ID:kidaa30,项目名称:magento2-platformsh,代码行数:14,代码来源:Special.php

示例15: aroundGetProductId

 /**
  * Get product id
  *
  * @param \Magento\Sales\Model\Order\Admin\Item $subject
  * @param callable $proceed
  * @param \Magento\Sales\Model\Order\Item $item
  *
  * @return int
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function aroundGetProductId(\Magento\Sales\Model\Order\Admin\Item $subject, \Closure $proceed, \Magento\Sales\Model\Order\Item $item)
 {
     if ($item->getProductType() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
         $productOptions = $item->getProductOptions();
         $product = $this->productFactory->create();
         return $product->getIdBySku($productOptions['simple_sku']);
     }
     return $proceed($item);
 }
开发者ID:pradeep-wagento,项目名称:magento2,代码行数:19,代码来源:Configurable.php


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