如何在Magento 2中的产品小部件的“添加到购物车”按钮中启用AJAX?


10

在Magento 2中,普通Add to Cart按钮具有非常好的基于AJAX的逻辑,可将产品添加到购物车。
但是,当我们Catalog Products List在CMS页面中使用小部件时,此产品列表中的按钮将与一起使用HTTP POST,以重新加载当前页面。

用户体验受此困扰,如果按钮具有与默认类别产品列表或产品页面中相同的AJAX逻辑,则将是可取的。

我们如何扩展Catalog Products List小部件以使其使用更好的 Add to Cart按钮?还是有其他解决方法?


我相信您的意思是“ CMS页面”,而不是“ CSS页面”。:)
Iveta Allogenes

@IvetaAllogenes编辑;-)
Jey DWork

Answers:


22

您必须覆盖addtocart.phtml文件

app/design/frontend/vendorname/themename/Magento_Catalog/templates/product/view/addtocart.phtml

现在,只需将“ bindSubmit”:false替换为“ bindSubmit”:true

<script type="text/x-magento-init">
    {
        "#product_addtocart_form": {
            "catalogAddToCart": {
                "bindSubmit": false
            }
        }
    }
</script>

<script type="text/x-magento-init">
    {
        "#product_addtocart_form": {
            "catalogAddToCart": {
                "bindSubmit": true
            }
        }
    }
</script>

现在删除缓存和page_cache文件夹或刷新缓存。

注意:请确保您必须从 Store->Configuration->Sales->Checkout->Shopping Cart->After Adding a Product Redirect to Shopping Cart to No


此代码在magento 2.2.3中不起作用。
阿什纳

我们如何能在grid.html 2.2.3添加添加AJAX到购物车的首页小部件
Ashna

@Prince patel,如何重新初始化?我已经安装了ajax滚动,因此响应后添加到购物车无法正常工作
jafar pinjar

@jafarpinjar这是默认的Magento代码。请检查ajax滚动模块是否存在此问题。
帕特尔王子(Patel Patel)

使用“ bindSubmit”更改此文件后,它对我有用:true
Sarfaraj Sipai'5

6

您可以Catalog Products List通过创建包含以下文件的模块,将扩展为使用ajax购物车:

/Your/Module/Block/Product/ListBlock.php内容:

<?php

namespace Your\Module\Block\Product;


use Magento\CatalogWidget\Block\Product\ProductsList;

class ListBlock extends ProductsList
{
    /**
     * @var \Magento\Framework\Url\Helper\Data
     */
    protected $urlHelper;

    public function __construct(
        \Magento\Catalog\Block\Product\Context $context,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        \Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
        \Magento\Framework\App\Http\Context $httpContext,
        \Magento\Rule\Model\Condition\Sql\Builder $sqlBuilder,
        \Magento\CatalogWidget\Model\Rule $rule,
        \Magento\Widget\Helper\Conditions $conditionsHelper,
        \Magento\Framework\Url\Helper\Data $urlHelper,
        array $data
    )
    {
        $this->urlHelper = $urlHelper;

        parent::__construct($context, $productCollectionFactory, $catalogProductVisibility, $httpContext, $sqlBuilder, $rule, $conditionsHelper, $data);
    }

    /**
     * Get post parameters
     *
     * @param \Magento\Catalog\Model\Product $product
     * @return string
     */
    public function getAddToCartPostParams(\Magento\Catalog\Model\Product $product)
    {
        $url = $this->getAddToCartUrl($product);
        return [
            'action' => $url,
            'data' => [
                'product' => $product->getEntityId(),
                \Magento\Framework\App\ActionInterface::PARAM_NAME_URL_ENCODED =>
                    $this->urlHelper->getEncodedUrl($url),
            ]
        ];
    }
}

您的/Module/etc/widget.xml包含以下内容:

<widgets xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Widget:etc/widget.xsd">
    <widget id="ajax_products_list" class="Your\Module\Block\Product\ListBlock" is_email_compatible="true"
            placeholder_image="Magento_CatalogWidget::images/products_list.png" ttl="86400">
        <label translate="true">Ajax Catalog Products List</label>
        <description translate="true">List of Products with Ajax Cart</description>
        <parameters>
            <parameter name="title" xsi:type="text" required="false" visible="true">
                <label translate="true">Title</label>
            </parameter>
            <parameter name="show_pager" xsi:type="select" visible="true"
                       source_model="Magento\Config\Model\Config\Source\Yesno">
                <label translate="true">Display Page Control</label>
            </parameter>
            <parameter name="products_per_page" xsi:type="text" required="true" visible="true">
                <label translate="true">Number of Products per Page</label>
                <depends>
                    <parameter name="show_pager" value="1" />
                </depends>
                <value>5</value>
            </parameter>
            <parameter name="products_count" xsi:type="text" required="true" visible="true">
                <label translate="true">Number of Products to Display</label>
                <value>10</value>
            </parameter>
            <parameter name="template" xsi:type="select" required="true" visible="true">
                <label translate="true">Template</label>
                <options>
                    <option name="default" value="Your_Module::product/widget/content/grid.phtml" selected="true">
                        <label translate="true">Products Grid Template</label>
                    </option>
                </options>
            </parameter>
            <parameter name="cache_lifetime" xsi:type="text" visible="true">
                <label translate="true">Cache Lifetime (Seconds)</label>
                <description translate="true">86400 by default, if not set. To refresh instantly, clear the Blocks HTML Output cache.</description>
            </parameter>
            <parameter name="condition" xsi:type="conditions" visible="true" required="true" sort_order="10"
                       class="Magento\CatalogWidget\Block\Product\Widget\Conditions">
                <label translate="true">Conditions</label>
            </parameter>
        </parameters>
        <containers>
            <container name="content">
                <template name="grid" value="default" />
            </container>
            <container name="content.top">
                <template name="grid" value="default" />
            </container>
            <container name="content.bottom">
                <template name="grid" value="default" />
            </container>
        </containers>
    </widget>
</widgets>

最后是带有内容的Your / Module / view / frontend / templates / product / widget / content / grid.phtml:

<?php

// @codingStandardsIgnoreFile
use Magento\Framework\App\Action\Action;
?>
<?php
/**
 * Template for displaying products list widget
 *
 * @var $block \Your\Module\Block\Product\ListBlock
 */
?>
<?php if ($exist = ($block->getProductCollection() && $block->getProductCollection()->getSize())):?>
<?php
    $type = 'widget-product-grid';

    $mode = 'grid';

    $image = 'new_products_content_widget_grid';
    $title = $block->getTitle() ? __($block->getTitle()) : '';
    $products = $block->getProductCollection()->getItems();
    $_helper = $this->helper('Magento\Catalog\Helper\Output');

    $showWishlist = true;
    $showCompare = true;
    $showCart = true;
    $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::DEFAULT_VIEW;
    $showDescription = false;
?>
    <div class="block widget block-products-list <?php /* @escapeNotVerified */ echo $mode; ?>">
        <?php if ($title):?>
        <div class="block-title">
            <strong><?php /* @escapeNotVerified */ echo $title; ?></strong>
        </div>
        <?php endif ?>
        <div class="block-content">
            <?php /* @escapeNotVerified */ echo '<!-- ' . $image . '-->' ?>
            <div class="products-<?php /* @escapeNotVerified */ echo $mode; ?> <?php /* @escapeNotVerified */ echo $mode; ?>">
                <ol class="product-items <?php /* @escapeNotVerified */ echo $type; ?>">
                    <?php $iterator = 1; ?>
                    <?php /** @var \Magento\Catalog\Model\Product $_product */ ?>
                    <?php foreach ($products as $_product): ?>
                        <?php /* @escapeNotVerified */ echo($iterator++ == 1) ? '<li class="product-item">' : '</li><li class="product-item">' ?>
                        <div class="product-item-info" data-container="product-grid">
                            <?php
                            $productImage = $block->getImage($_product, $image);
                            ?>
                            <?php // Product Image ?>
                            <a href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" class="product photo product-item-photo" tabindex="-1">
                                <?php echo $productImage->toHtml(); ?>
                            </a>
                            <div class="product details product-item-details">
                                <?php
                                $_productNameStripped = $block->stripTags($_product->getName(), null, true);
                                ?>
                                <strong class="product name product-item-name">
                                    <a class="product-item-link"
                                       href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>">
                                        <?php /* @escapeNotVerified */ echo $_helper->productAttribute($_product, $_product->getName(), 'name'); ?>
                                    </a>
                                </strong>
                                <?php echo $block->getReviewsSummaryHtml($_product, $templateType); ?>
                                <?php /* @escapeNotVerified */ echo $block->getProductPrice($_product) ?>
                                <?php echo $block->getProductDetailsHtml($_product); ?>

                                <div class="product-item-inner">
                                    <div class="product actions product-item-actions">
                                        <div class="actions-primary">
                                            <?php if ($_product->isSaleable()): ?>
                                                <?php $postParams = $block->getAddToCartPostParams($_product); ?>
                                                <form data-role="tocart-form" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post">
                                                    <input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $postParams['data']['product']; ?>">
                                                    <input type="hidden" name="<?php /* @escapeNotVerified */ echo Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php /* @escapeNotVerified */ echo $postParams['data'][Action::PARAM_NAME_URL_ENCODED]; ?>">
                                                    <?php echo $block->getBlockHtml('formkey')?>
                                                    <button type="submit"
                                                            title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"
                                                            class="action tocart primary">
                                                        <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
                                                    </button>
                                                </form>
                                            <?php else: ?>
                                                <?php if ($_product->getIsSalable()): ?>
                                                    <div class="stock available"><span><?php /* @escapeNotVerified */ echo __('In stock') ?></span></div>
                                                <?php else: ?>
                                                    <div class="stock unavailable"><span><?php /* @escapeNotVerified */ echo __('Out of stock') ?></span></div>
                                                <?php endif; ?>
                                            <?php endif; ?>
                                        </div>
                                        <div data-role="add-to-links" class="actions-secondary">
                                            <?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow()): ?>
                                                <a href="#"
                                                   class="action towishlist"
                                                   title="<?php echo $block->escapeHtml(__('Add to Wish List')); ?>"
                                                   aria-label="<?php echo $block->escapeHtml(__('Add to Wish List')); ?>"
                                                   data-post='<?php /* @escapeNotVerified */ echo $block->getAddToWishlistParams($_product); ?>'
                                                   data-action="add-to-wishlist"
                                                   role="button">
                                                    <span><?php /* @escapeNotVerified */ echo __('Add to Wish List') ?></span>
                                                </a>
                                            <?php endif; ?>
                                            <?php
                                            $compareHelper = $this->helper('Magento\Catalog\Helper\Product\Compare');
                                            ?>
                                            <a href="#"
                                               class="action tocompare"
                                               title="<?php echo $block->escapeHtml(__('Add to Compare')); ?>"
                                               aria-label="<?php echo $block->escapeHtml(__('Add to Compare')); ?>"
                                               data-post='<?php /* @escapeNotVerified */ echo $compareHelper->getPostDataParams($_product); ?>'
                                               role="button">
                                                <span><?php /* @escapeNotVerified */ echo __('Add to Compare') ?></span>
                                            </a>
                                        </div>
                                    </div>
                                    <?php if ($showDescription):?>
                                        <div class="product description product-item-description">
                                            <?php /* @escapeNotVerified */ echo $_helper->productAttribute($_product, $_product->getShortDescription(), 'short_description') ?>
                                            <a href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>" title="<?php /* @escapeNotVerified */ echo $_productNameStripped ?>"
                                               class="action more"><?php /* @escapeNotVerified */ echo __('Learn More') ?></a>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        <?php echo($iterator == count($products)+1) ? '</li>' : '' ?>
                    <?php endforeach ?>
                </ol>
            </div>
            <?php echo $block->getPagerHtml() ?>
        </div>
    </div>
    <?php if (!$block->isRedirectToCartEnabled()) : ?>
        <script type="text/x-magento-init">
        {
            "[data-role=tocart-form], .form.map.checkout": {
                "catalogAddToCart": {}
            }
        }
        </script>
    <?php endif; ?>
<?php endif;?>

确保使用自己的名称空间替换“您的\模块”的所有实例。


1
不确定您在phtml填充中所做的更改。您能否通过说出您更改的内容以及原因(其他填充内容很简单)来清除问题
CompactCode

2

在Magento 2.2中,Magento_Catalog/product/view/validation脚本被称为而不是catalogAddToCart

它已经存在addtocart.phtml(带有radioCheckboxClosestconfig选项),因此要启用Ajax Add to Cart,只需添加以下bindSubmit选项:

<script type="text/x-magento-init">
{
    "#product_addtocart_form": {
        "Magento_Catalog/product/view/validation": {
            "bindSubmit": true,
            "radioCheckboxClosest": ".nested"
        }
    }
}
</script>

添加此设置对我不起作用
Joshua Flood

在v2.2.3中完美工作,谢谢!
Kristjan O.

1

在最新的Magento 2版本中,此功能已再次更改,现在是

<script type="text/x-magento-init">
    {
        "#product_addtocart_form": {
            "Magento_Catalog/js/validate-product": {
                "bindSubmit": true
            }
        }
    }
</script>

1

Magento 2.3解决方案

对于小部件目录产品列表:

在这种情况下,您应该找到小部件的模板

module-catalog-widget / view / frontend / templates / product / widget / content / grid.phtml

并插入以下代码:

<script type="text/x-magento-init">
    {
        "[data-role=tocart-form], .form.map.checkout": {
            "catalogAddToCart": {}
        }
    }
</script>

它工作正常。谢谢。
阿吉
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.