前台获取显示可配置产品库存

magento 收藏
0 58
app/code/[Vendor]/[Module]/Helper/Stock.php


<?php
namespace [Vendor]\[Module]\Helper;

class Stock extends \Magento\Framework\App\Helper\AbstractHelper
{
/**
* @var Magento\CatalogInventory\Api\StockStateInterface
*/
protected $stockState;

/**
* Output constructor.
* @param \Magento\Framework\App\Helper\Context $context
* @param \Magento\CatalogInventory\Api\StockStateInterface $stockState
*/
public function __construct(
\Magento\Framework\App\Helper\Context $context,
\Magento\CatalogInventory\Api\StockStateInterface $stockState
) {
$this->stockState = $stockState;
parent::__construct($context);
}

/**
* Retrieve stock qty whether product
*
* @param int $productId
* @param int $websiteId
* @return float
*/
public function getStockQty($product, $websiteId = null)
{
$_productId = $product->getId();
if($product->getTypeId() != 'configurable') {
return $this->stockState->getStockQty($_productId, $websiteId);
}
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$configProduct = $objectManager->create('Magento\Catalog\Model\Product')->load($_productId);

$_children = $configProduct->getTypeInstance()->getUsedProducts($configProduct);

$_stockQty = 0;

foreach ($_children as $child){
$_stockQty += $this->stockState->getStockQty($child->getId(), $websiteId);
}
return $_stockQty;
}
}


在可获取产品信息的ptml文件中


<?php
$_product = $block->getProduct();

$_helperStock = $this->helper([Vendor]\[Module]\Helper\Stock::class);

echo $_helperStock->getStockQty($_product, $_product->getStore()->getWebsiteId());

?>


    暂时没有人评论
精选帖子
热门帖子
1创建flutter应用 93
2js 变量命令法 92
3回流和重绘 92
4js 添加邮箱验证 91
5应用配置 91
6flutter 构建模式 90
7在phtml中使用图片 89
8作用域 89
9v-if 和 v-else 89