magento - 在 addtocart.phtml 的 Magento 2.2.6 中,我怎样才能获得“数量增量”
问题描述
在 Magento 2.2.6 中的文件
"/app/design/frontend/THEME/Magento_Catalog/templates/product/view/addtocart.phtml"
如何获得我在屏幕截图中设置的“数量增量”?
我做了很多测试,但它们不起作用,例如:
<?php echo $product->getStockItem()->getData('qty_increments') ?>
<?php echo $block->getProductQtyIncrements() ?>
<?php echo $stockItem->getQtyIncrements() ?>
<?php echo $product->getStockItem()->getQtyIncrements() ?>
解决方案
这是 Magento 2.2 及更高版本的解决方案,使用视图模型方法。文档:https ://devdocs.magento.com/guides/v2.3/extension-dev-guide/view-models.html
使用以下文件创建自定义模块
应用程序/代码/供应商/模块名称/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
<type name="Vendor\ModuleName\ViewModel\Qty" />
</config>
应用程序/代码/供应商/模块名称/etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="Vendor_ModuleName" setup_version="1.0.0" />
</config>
app/code/Vendor/ModuleName/view/frontend/layout/catalog_product_view.xml
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<body>
<referenceBlock name="product.info.addtocart.additional" template="Vendor_ModuleName::product/view/addtocart.phtml">
<arguments>
<argument name="view_model" xsi:type="object">Vendor\ModuleName\ViewModel\Qty</argument>
</arguments>
</referenceBlock>
<referenceBlock name="product.info.addtocart" template="Vendor_ModuleName::product/view/addtocart.phtml">
<arguments>
<argument name="view_model" xsi:type="object">Vendor\ModuleName\ViewModel\Qty</argument>
</arguments>
</referenceBlock>
</body>
</page>
app/code/Vendor/ModuleName/ViewModel/Qty.php
无需创建自定义函数,因为扩展“Qtyincrements”类就足够了。
<?php
namespace Vendor\ModuleName\ViewModel;
use Magento\Framework\View\Element\Block\ArgumentInterface;
use Magento\CatalogInventory\Block\Qtyincrements;
class Qty extends Qtyincrements implements ArgumentInterface {}
app/code/Vendor/ModuleName/view/frontend/templates/product/view/addtocart.phtml
现在您可以通过 viewModel 访问 getProductQtyIncrements() ,如下所示:
...
<?php $viewModel = $block->getViewModel(); ?>
<?php $productQtyIncrements = $viewModel->getProductQtyIncrements(); ?>
...
希望这对未来的读者有用。如果它对您有用,请点赞。
推荐阅读
- c# - JsonSerializationException 解析
- javascript - Javascript将文件从网页上传到特定的谷歌驱动器帐户
- php - 我使用 netbeans,我想运行我的 PHP 应用程序,我已经在我的机器上安装了 xampp 和 wampserver
- python - 使用套接字在python中发送数据
- java - 在 JPA 中对具有多对多关系的对象执行 NOT IN QUERY
- javascript - 当 CKEditor mangles 时,如何在其中包含带有 HTML 的工具提示
- python - Python Click:如何打印有关使用错误的完整帮助详细信息?
- javascript - 我的函数中的逻辑错误阻止 count++ 工作
- json - Powershell Json 对象操作
- macos - 缩放不适用于 Mac 上 matplotlib 中的 3d 图