下拉列表是可配置产品上使用的属性
创建插件
namespace Vendor\Module\Plugin;
class Configurable
{
public function aftergetJsonConfig(
\Magento\ConfigurableProduct\Block\Product\View\Type\Configurable $subject,
$result
) {
$jsonResult = json_decode($result, true);
$jsonResult['stockqtys']=[];
foreach ($subject->getAllowProducts() as $simpleProduct) {
$jsonResult['stockqtys'][$simpleProduct->getId()] = $this->getProductStock($simpleProduct->getId());
}
$result = json_encode($jsonResult);
return $result;
}
public function getProductStock($productId)
{
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$stockRegistry = $objectManager->get('\Magento\CatalogInventory\Api\StockRegistryInterface');
return $stockRegistry->getStockItem($productId)->getQty();
}
}
创建 etc\di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<type name="Magento\ConfigurableProduct\Block\Product\View\Type\Configurable">
<plugin disabled="false" name="Vendor_Module_Plugin" sortOrder="10" type="Vendor\Module\Plugin\Configurable"/>
</type>
</config>
查看/前端/web/js/stockswitch.js
define([
'jquery',
'mage/utils/wrapper'
], function ($, wrapper) {
'use strict';
return function(targetModule){
var reloadPrice = targetModule.prototype._reloadPrice;
var reloadPriceWrapper = wrapper.wrap(reloadPrice, function(original){
var result = original();
var productStock = this.options.spConfig.stockqtys[this.simpleProduct];
$('div.product-info-main .stock .value').html("");
if(productStock != '') {
$('div.product-info-main .stock .value').html(productStock);
}
return result;
});
targetModule.prototype._reloadPrice = reloadPriceWrapper;
return targetModule;
};
});
查看/前端/requirejs-config.js
var config = {
config: {
mixins: {
'Magento_ConfigurableProduct/js/configurable': {
'Vendor_Module/js/stockswitch': true
}
}
}
};
覆盖 default.phtml 模板并在下面添加您希望您的股票出现的行
供应商/模块/Magento_Catalog/templates/product/view/type/default.phtml
<div class="stock actual-qty"> <span class="value" > </span> </div>
请让我知道 cmets 的任何改进