本文整理汇总了PHP中Magento\Catalog\Helper\Product类的典型用法代码示例。如果您正苦于以下问题:PHP Product类的具体用法?PHP Product怎么用?PHP Product使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Product类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: __construct
/**
* @param Action\Context $context
* @param \Magento\Catalog\Helper\Product $productHelper
* @param \Magento\Framework\Escaper $escaper
* @param PageFactory $resultPageFactory
* @param ForwardFactory $resultForwardFactory
*/
public function __construct(Action\Context $context, \Magento\Catalog\Helper\Product $productHelper, \Magento\Framework\Escaper $escaper, PageFactory $resultPageFactory, ForwardFactory $resultForwardFactory)
{
parent::__construct($context);
$productHelper->setSkipSaleableCheck(true);
$this->escaper = $escaper;
$this->resultPageFactory = $resultPageFactory;
$this->resultForwardFactory = $resultForwardFactory;
}
示例2: convertAttribute
/**
* Set current attribute to entry (for specified product)
*
* @param \Magento\Catalog\Model\Product $product
* @param \Magento\Framework\Gdata\Gshopping\Entry $entry
* @return \Magento\Framework\Gdata\Gshopping\Entry
*/
public function convertAttribute($product, $entry)
{
$url = $this->_catalogProduct->getImageUrl($product);
if ($product->getImage() && $product->getImage() != 'no_selection' && $url) {
$this->_setAttribute($entry, 'image_link', self::ATTRIBUTE_TYPE_URL, $url);
}
return $entry;
}
示例3: __construct
/**
* @param \Magento\Framework\Data\Form\Element\Factory $factoryElement
* @param \Magento\Framework\Data\Form\Element\CollectionFactory $factoryCollection
* @param \Magento\Framework\Escaper $escaper
* @param \Magento\Catalog\Helper\Product $helper
* @param array $data
*/
public function __construct(\Magento\Framework\Data\Form\Element\Factory $factoryElement, \Magento\Framework\Data\Form\Element\CollectionFactory $factoryCollection, \Magento\Framework\Escaper $escaper, \Magento\Catalog\Helper\Product $helper, array $data = [])
{
$this->_helper = $helper;
$this->_virtual = $factoryElement->create('checkbox');
$this->_virtual->setId(self::VIRTUAL_FIELD_HTML_ID)->setName('is_virtual')->setLabel($this->_helper->getTypeSwitcherControlLabel());
$data['class'] = 'validate-number validate-zero-or-greater validate-number-range number-range-0-99999999.9999';
parent::__construct($factoryElement, $factoryCollection, $escaper, $data);
}
示例4: getOptions
/**
* @return array
*/
public function getOptions()
{
if (!$this->options) {
$product = $this->getProduct();
$typeInstance = $product->getTypeInstance();
$typeInstance->setStoreFilter($product->getStoreId(), $product);
$optionCollection = $typeInstance->getOptionsCollection($product);
$selectionCollection = $typeInstance->getSelectionsCollection($typeInstance->getOptionsIds($product), $product);
$this->options = $optionCollection->appendSelections($selectionCollection, false, $this->catalogProduct->getSkipSaleableCheck());
}
return $this->options;
}
示例5: getLastViewedUrl
/**
* Retrieve Visitor/Customer Last Viewed URL
*
* @return string
*/
public function getLastViewedUrl()
{
$productId = $this->_catalogSession->getLastViewedProductId();
if ($productId) {
try {
$product = $this->productRepository->getById($productId);
} catch (NoSuchEntityException $e) {
return '';
}
/* @var $product \Magento\Catalog\Model\Product */
if ($this->_catalogProduct->canShow($product, 'catalog')) {
return $product->getProductUrl();
}
}
$categoryId = $this->_catalogSession->getLastViewedCategoryId();
if ($categoryId) {
try {
$category = $this->categoryRepository->get($categoryId);
} catch (NoSuchEntityException $e) {
return '';
}
/* @var $category \Magento\Catalog\Model\Category */
if (!$this->_catalogCategory->canShow($category)) {
return '';
}
return $category->getCategoryUrl();
}
return '';
}
示例6: 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);
}
示例7: _prepareLayout
/**
* Add meta information from product to head block
*
* @return \Magento\Catalog\Block\Product\View
*/
protected function _prepareLayout()
{
$this->getLayout()->createBlock('Magento\\Catalog\\Block\\Breadcrumbs');
$product = $this->getProduct();
if (!$product) {
return parent::_prepareLayout();
}
$title = $product->getMetaTitle();
if ($title) {
$this->pageConfig->getTitle()->set($title);
}
$keyword = $product->getMetaKeyword();
$currentCategory = $this->_coreRegistry->registry('current_category');
if ($keyword) {
$this->pageConfig->setKeywords($keyword);
} elseif ($currentCategory) {
$this->pageConfig->setKeywords($product->getName());
}
$description = $product->getMetaDescription();
if ($description) {
$this->pageConfig->setDescription($description);
} else {
$this->pageConfig->setDescription($this->string->substr($product->getDescription(), 0, 255));
}
if ($this->_productHelper->canUseCanonicalTag()) {
$this->pageConfig->addRemotePageAsset($product->getUrlModel()->getUrl($product, ['_ignore_category' => true]), 'canonical', ['attributes' => ['rel' => 'canonical']]);
}
$pageMainTitle = $this->getLayout()->getBlock('page.main.title');
if ($pageMainTitle) {
$pageMainTitle->setPageTitle($product->getName());
}
return parent::_prepareLayout();
}
示例8: create
/**
* {@inheritdoc}
*/
public function create(\Magento\Catalog\Service\V1\Data\Eav\AttributeMetadata $attributeMetadata)
{
/**
* @var $model \Magento\Catalog\Model\Resource\Eav\Attribute
*/
$model = $this->attributeFactory->create();
$data = $attributeMetadata->__toArray();
// unset attribute id because we create new attribute (does not rewrite existing one)
unset($data[AttributeMetadata::ATTRIBUTE_ID]);
// define frontend label
if (!$attributeMetadata->getFrontendLabel()) {
throw InputException::requiredField(AttributeMetadata::FRONTEND_LABEL);
}
$data[AttributeMetadata::FRONTEND_LABEL] = [];
foreach ($attributeMetadata->getFrontendLabel() as $label) {
$data[AttributeMetadata::FRONTEND_LABEL][$label->getStoreId()] = $label->getLabel();
}
if (!isset($data[AttributeMetadata::FRONTEND_LABEL][0]) || !$data[AttributeMetadata::FRONTEND_LABEL][0]) {
throw InputException::invalidFieldValue(AttributeMetadata::FRONTEND_LABEL, null);
}
$data[AttributeMetadata::ATTRIBUTE_CODE] = $attributeMetadata->getAttributeCode() ?: $this->generateCode($data[AttributeMetadata::FRONTEND_LABEL][0]);
$this->validateCode($data[AttributeMetadata::ATTRIBUTE_CODE]);
$this->validateFrontendInput($attributeMetadata->getFrontendInput());
$data[AttributeMetadata::BACKEND_TYPE] = $model->getBackendTypeByInput($attributeMetadata->getFrontendInput());
$data[AttributeMetadata::SOURCE_MODEL] = $this->helper->getAttributeSourceModelByInputType($attributeMetadata->getFrontendInput());
$data[AttributeMetadata::BACKEND_MODEL] = $this->helper->getAttributeBackendModelByInputType($attributeMetadata->getFrontendInput());
$model->addData($data);
$model->setEntityTypeId($this->eavConfig->getEntityType(\Magento\Catalog\Model\Product::ENTITY)->getId())->setIsUserDefined(1);
return $model->save()->getAttributeCode();
}
示例9: checkProductBuyState
/**
* Check if product can be bought
*
* @param \Magento\Catalog\Model\Product $product
* @return $this
* @throws \Magento\Framework\Exception\LocalizedException
*/
public function checkProductBuyState($product)
{
parent::checkProductBuyState($product);
$productOptionIds = $this->getOptionsIds($product);
$productSelections = $this->getSelectionsCollection($productOptionIds, $product);
$selectionIds = $product->getCustomOption('bundle_selection_ids');
$selectionIds = unserialize($selectionIds->getValue());
$buyRequest = $product->getCustomOption('info_buyRequest');
$buyRequest = new \Magento\Framework\DataObject(unserialize($buyRequest->getValue()));
$bundleOption = $buyRequest->getBundleOption();
if (empty($bundleOption)) {
throw new \Magento\Framework\Exception\LocalizedException($this->getSpecifyOptionMessage());
}
$skipSaleableCheck = $this->_catalogProduct->getSkipSaleableCheck();
foreach ($selectionIds as $selectionId) {
/* @var $selection \Magento\Bundle\Model\Selection */
$selection = $productSelections->getItemById($selectionId);
if (!$selection || !$selection->isSalable() && !$skipSaleableCheck) {
throw new \Magento\Framework\Exception\LocalizedException(__('The required options you selected are not available.'));
}
}
$product->getTypeInstance()->setStoreFilter($product->getStoreId(), $product);
$optionsCollection = $this->getOptionsCollection($product);
foreach ($optionsCollection->getItems() as $option) {
if ($option->getRequired() && empty($bundleOption[$option->getId()])) {
throw new \Magento\Framework\Exception\LocalizedException(__('Please select all required options.'));
}
}
return $this;
}
示例10: execute
/**
* Add wishlist item to shopping cart and remove from wishlist
*
* If Product has required options - item removed from wishlist and redirect
* to product view page with message about needed defined required options
*
* @return ResponseInterface
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function execute()
{
$itemId = (int) $this->getRequest()->getParam('item');
/* @var $item \Magento\Wishlist\Model\Item */
$item = $this->itemFactory->create()->load($itemId);
if (!$item->getId()) {
return $this->_redirect('*/*');
}
$wishlist = $this->wishlistProvider->getWishlist($item->getWishlistId());
if (!$wishlist) {
return $this->_redirect('*/*');
}
// Set qty
$qty = $this->getRequest()->getParam('qty');
if (is_array($qty)) {
if (isset($qty[$itemId])) {
$qty = $qty[$itemId];
} else {
$qty = 1;
}
}
$qty = $this->quantityProcessor->process($qty);
if ($qty) {
$item->setQty($qty);
}
$redirectUrl = $this->_url->getUrl('*/*');
$configureUrl = $this->_url->getUrl('*/*/configure/', ['id' => $item->getId(), 'product_id' => $item->getProductId()]);
try {
/** @var \Magento\Wishlist\Model\Resource\Item\Option\Collection $options */
$options = $this->optionFactory->create()->getCollection()->addItemFilter([$itemId]);
$item->setOptions($options->getOptionsByItem($itemId));
$buyRequest = $this->productHelper->addParamsToBuyRequest($this->getRequest()->getParams(), ['current_config' => $item->getBuyRequest()]);
$item->mergeBuyRequest($buyRequest);
$item->addToCart($this->cart, true);
$this->cart->save()->getQuote()->collectTotals();
$wishlist->save();
if (!$this->cart->getQuote()->getHasError()) {
$message = __('You added %1 to your shopping cart.', $this->escaper->escapeHtml($item->getProduct()->getName()));
$this->messageManager->addSuccess($message);
}
if ($this->cart->getShouldRedirectToCart()) {
$redirectUrl = $this->cart->getCartUrl();
} else {
$refererUrl = $this->_redirect->getRefererUrl();
if ($refererUrl && $refererUrl != $configureUrl) {
$redirectUrl = $refererUrl;
}
}
} catch (ProductException $e) {
$this->messageManager->addError(__('This product(s) is out of stock.'));
} catch (\Magento\Framework\Exception\LocalizedException $e) {
$this->messageManager->addNotice($e->getMessage());
$redirectUrl = $configureUrl;
} catch (\Exception $e) {
$this->messageManager->addException($e, __('Cannot add item to shopping cart'));
}
$this->helper->calculate();
return $this->getResponse()->setRedirect($redirectUrl);
}
示例11: updateItem
/**
* Update wishlist Item and set data from request
*
* The $params sets how current item configuration must be taken into account and additional options.
* It's passed to \Magento\Catalog\Helper\Product->addParamsToBuyRequest() to compose resulting buyRequest.
*
* Basically it can hold
* - 'current_config', \Magento\Framework\Object or array - current buyRequest that configures product in this item,
* used to restore currently attached files
* - 'files_prefix': string[a-z0-9_] - prefix that was added at frontend to names of file options (file inputs),
* so they won't intersect with other submitted options
*
* For more options see \Magento\Catalog\Helper\Product->addParamsToBuyRequest()
*
* @param int|Item $itemId
* @param \Magento\Framework\Object $buyRequest
* @param null|array|\Magento\Framework\Object $params
* @return $this
* @throws Exception
*
* @see \Magento\Catalog\Helper\Product::addParamsToBuyRequest()
*/
public function updateItem($itemId, $buyRequest, $params = null)
{
$item = null;
if ($itemId instanceof Item) {
$item = $itemId;
} else {
$item = $this->getItem((int) $itemId);
}
if (!$item) {
throw new Exception(__('We can\'t specify a wish list item.'));
}
$product = $item->getProduct();
$productId = $product->getId();
if ($productId) {
if (!$params) {
$params = new \Magento\Framework\Object();
} else {
if (is_array($params)) {
$params = new \Magento\Framework\Object($params);
}
}
$params->setCurrentConfig($item->getBuyRequest());
$buyRequest = $this->_catalogProduct->addParamsToBuyRequest($buyRequest, $params);
$product->setWishlistStoreId($item->getStoreId());
$items = $this->getItemCollection();
$isForceSetQuantity = true;
foreach ($items as $_item) {
/* @var $_item Item */
if ($_item->getProductId() == $product->getId() && $_item->representProduct($product) && $_item->getId() != $item->getId()) {
// We do not add new wishlist item, but updating the existing one
$isForceSetQuantity = false;
}
}
$resultItem = $this->addNewItem($product, $buyRequest, $isForceSetQuantity);
/**
* Error message
*/
if (is_string($resultItem)) {
throw new Exception(__($resultItem));
}
if ($resultItem->getId() != $itemId) {
if ($resultItem->getDescription() != $item->getDescription()) {
$resultItem->setDescription($item->getDescription())->save();
}
$item->isDeleted(true);
$this->setDataChanges(true);
} else {
$resultItem->setQty($buyRequest->getQty() * 1);
$resultItem->setOrigData('qty', 0);
}
} else {
throw new Exception(__('The product does not exist.'));
}
return $this;
}
示例12: save
/**
* {@inheritdoc}
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
* @SuppressWarnings(PHPMD.NPathComplexity)
*/
public function save(\Magento\Catalog\Api\Data\ProductAttributeInterface $attribute)
{
if ($attribute->getAttributeId()) {
$existingModel = $this->get($attribute->getAttributeCode());
if (!$existingModel->getAttributeId()) {
throw NoSuchEntityException::singleField('attribute_code', $existingModel->getAttributeCode());
}
$attribute->setAttributeId($existingModel->getAttributeId());
$attribute->setIsUserDefined($existingModel->getIsUserDefined());
$attribute->setFrontendInput($existingModel->getFrontendInput());
if (is_array($attribute->getFrontendLabels())) {
$frontendLabel[0] = $existingModel->getDefaultFrontendLabel();
foreach ($attribute->getFrontendLabels() as $item) {
$frontendLabel[$item->getStoreId()] = $item->getLabel();
}
$attribute->setDefaultFrontendLabel($frontendLabel);
}
if (!$attribute->getIsUserDefined()) {
// Unset attribute field for system attributes
$attribute->setApplyTo(null);
}
} else {
$attribute->setAttributeId(null);
if (!$attribute->getFrontendLabels() && !$attribute->getDefaultFrontendLabel()) {
throw InputException::requiredField('frontend_label');
}
$frontendLabels = [];
if ($attribute->getDefaultFrontendLabel()) {
$frontendLabels[0] = $attribute->getDefaultFrontendLabel();
}
if ($attribute->getFrontendLabels() && is_array($attribute->getFrontendLabels())) {
foreach ($attribute->getFrontendLabels() as $label) {
$frontendLabels[$label->getStoreId()] = $label->getLabel();
}
if (!isset($frontendLabels[0]) || !$frontendLabels[0]) {
throw InputException::invalidFieldValue('frontend_label', null);
}
$attribute->setDefaultFrontendLabel($frontendLabels);
}
$attribute->setAttributeCode($attribute->getAttributeCode() ?: $this->generateCode($frontendLabels[0]));
$this->validateCode($attribute->getAttributeCode());
$this->validateFrontendInput($attribute->getFrontendInput());
$attribute->setBackendType($attribute->getBackendTypeByInput($attribute->getFrontendInput()));
$attribute->setSourceModel($this->productHelper->getAttributeSourceModelByInputType($attribute->getFrontendInput()));
$attribute->setBackendModel($this->productHelper->getAttributeBackendModelByInputType($attribute->getFrontendInput()));
$attribute->setEntityTypeId($this->eavConfig->getEntityType(\Magento\Catalog\Api\Data\ProductAttributeInterface::ENTITY_TYPE_CODE)->getId());
$attribute->setIsUserDefined(1);
}
$this->attributeResource->save($attribute);
foreach ($attribute->getOptions() as $option) {
$this->optionManagement->add($attribute->getAttributeCode(), $option);
}
return $this->get($attribute->getAttributeCode());
}
示例13: testPrepareProductOptions
public function testPrepareProductOptions()
{
/** @var $product \Magento\Catalog\Model\Product */
$product = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Catalog\\Model\\Product');
$buyRequest = new \Magento\Framework\DataObject(['qty' => 100, 'options' => ['option' => 'value']]);
$this->_helper->prepareProductOptions($product, $buyRequest);
$result = $product->getPreconfiguredValues();
$this->assertInstanceOf('Magento\\Framework\\DataObject', $result);
$this->assertEquals(100, $result->getQty());
$this->assertEquals(['option' => 'value'], $result->getOptions());
}
示例14: getAllowProducts
/**
* Get Allowed Products
*
* @return array
*/
public function getAllowProducts()
{
if (!$this->hasAllowProducts()) {
$products = [];
$skipSaleableCheck = $this->catalogProduct->getSkipSaleableCheck();
$allProducts = $this->getProduct()->getTypeInstance()->getUsedProducts($this->getProduct(), null);
foreach ($allProducts as $product) {
if ($product->isSaleable() || $skipSaleableCheck) {
$products[] = $product;
}
}
$this->setAllowProducts($products);
}
return $this->getData('allow_products');
}
示例15: execute
/**
* Add new product attrubute into all attribute sets.
* If attribute is already exists - skip.
*
* @param array $data Array of slider data arrays
* <pre>
* [
* attribute_code
* is_global
* frontend_input [text|boolean|textarea|select|price|media_image|etc]
* default_value_text
* is_searchable
* is_visible_in_advanced_search
* is_comparable
* frontend_label array
* sort_order Set 0 to use MaxSortOrder
* ]
* </pre>
* @return void
*/
public function execute($data)
{
$defaults = array('is_global' => 0, 'frontend_input' => 'boolean', 'is_configurable' => 0, 'is_filterable' => 0, 'is_filterable_in_search' => 0, 'sort_order' => 1);
$entityTypeId = $this->objectManager->create('Magento\\Eav\\Model\\Entity')->setType(\Magento\Catalog\Model\Product::ENTITY)->getTypeId();
$attributeSets = $this->objectManager->create('Magento\\Eav\\Model\\ResourceModel\\Entity\\Attribute\\Set\\Collection')->setEntityTypeFilter($entityTypeId);
foreach ($data as $itemData) {
/* @var $model \Magento\Catalog\Model\ResourceModel\Eav\Attribute */
$model = $this->attributeFactory->create()->load($itemData['attribute_code'], 'attribute_code');
if ($model->getId()) {
continue;
}
$itemData = array_merge($itemData, $defaults);
$itemData['source_model'] = $this->productHelper->getAttributeSourceModelByInputType($itemData['frontend_input']);
$itemData['backend_model'] = $this->productHelper->getAttributeBackendModelByInputType($itemData['frontend_input']);
$itemData['backend_type'] = $model->getBackendTypeByInput($itemData['frontend_input']);
$model->addData($itemData);
$model->setEntityTypeId($entityTypeId);
$model->setIsUserDefined(1);
foreach ($attributeSets as $set) {
$model->setAttributeSetId($set->getId());
$model->setAttributeGroupId($set->getDefaultGroupId());
try {
$model->save();
} catch (\Exception $e) {
$this->fault('product_attribute_save', $e);
}
}
if (!$attributeSets->count()) {
try {
$model->save();
} catch (\Exception $e) {
$this->fault('product_attribute_save', $e);
}
}
}
}