首页 > 解决方案 > 在 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() ?>

截图数量增量

标签: magentomagento2

解决方案


这是 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(); ?>
...

希望这对未来的读者有用。如果它对您有用,请点赞。


推荐阅读