有时我们想直接从分类页面预览产品,但不幸的是,这在默认情况下无法实现,所以我为它创建了简单的扩展。

基本的想法是在分类产品列表的产品上添加“Quick view”按钮,点击该按钮将打开弹窗显示产品的所有功能,通常仅在产品视图页面上可用。

 

入门

创建app/code/Magease/QuickView/registration.php并添加以下代码:

<?php
/**
 * @category    Magease
 * @package     Magease_QuickView
 */
 
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magease_QuickView',
    __DIR__
);

我们需要这个来注册我们的新模块。

之后创建app/code/Magease/QuickView/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="Magease_QuickView" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
            <module name="Magento_Customer"/>
        </sequence>
    </module>
</config>

app/code/Magease/QuickView/composer.json

{
  "name": "magease/module-quickview",
  "description": "N/A",
  "require": {
    "php": "~5.6.0|~7.0.0",
    "magento/framework": "100.1.*"
  },
  "type": "magento2-module",
  "version": "1.0.0",
  "license": [
    "proprietary"
  ],
  "autoload": {
    "files": [
      "registration.php"
    ],
    "psr-4": {
      "Magease\\QuickView\\": ""
    }
  }
}

此时,您应该运行下面命令启用此模块:

php bin/magento module:enable Magease_QuickView

 

添加功能

让我们首先在类别页面的每个产品盒上添加快速预览按钮。

创建app/code/Magease/QuickView/view/frontend/layout/catalog_category_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>
        <referenceContainer name="content">
            <referenceBlock name="category.product.addto">
                <block class="Magento\Catalog\Block\Product\ProductList\Item\Block"
                       name="category.product.quickview"
                       as="quickview"
                       template="Magease_QuickView::product/productlist/item/quickview.phtml"/>
            </referenceBlock>
        </referenceContainer>
    </body>
</page>

这将在“Add to cart”按钮附近添加按钮,你可以按你想要的风格设计。

创建app/code/Magease/QuickView/etc/frontend/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">
 
    <preference for="Magento\Catalog\Controller\Product\View"
                type="Magease\QuickView\Controller\Product\View" />
</config>

现在我们需要创建app/code/Magease/QuickView/Controller/Product/View.php

<?php
 
namespace Magease\QuickView\Controller\Product;
 
use Magento\Catalog\Controller\Product\View as CatalogView;
 
/**
 * Class View
 *
 * @package Magease\QuickView\Controller\Product
 */
class View extends CatalogView
{
    /**
     * Overriden in order to add new layout handle in case product page is loaded in iframe
     *
     * @return \Magento\Framework\Controller\Result\Forward|\Magento\Framework\Controller\Result\Redirect
     */
    public function execute()
    {
        if ($this->getRequest()->getParam("iframe")) {
            $layout = $this->_view->getLayout();
            $layout->getUpdate()->addHandle('quickview_product_view');
        }
        return parent::execute();
    }
}

这意味着当我们使用iframe作为GET参数调用产品的URL时,我们将能够修改其布局,因为在这种情况下我们有全新的句柄。
所以,让我们这样做:
app/code/Magease/QuickView/view/frontend/layout/quickview_product_view.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="empty"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
 
    <update handle="empty"/>
 
    <html>
        <attribute name="class" value="quickview-scroll"/>
    </html>
 
    <body>
        <attribute name="class" value="quickview-override"/>
 
        <referenceContainer name="product.page.products.wrapper" remove="true" />
        <referenceContainer name="product.info.details" remove="true" />
        <referenceBlock name="reviews.tab" remove="true" />
        <referenceBlock name="product.info.details" remove="true" />
        <referenceBlock name="product.info.description" remove="true" />
        <referenceBlock name="product.info.overview" remove="true" />
        <referenceBlock name="authentication-popup" remove="true" />
    </body>
</page>

 

JavaScript

app/code/Magease/QuickView/view/frontend/web/js/product/productlist/item/quickview.js

define([
    'jquery',
    'Magento_Ui/js/modal/modal',
    'mage/loader',
    'Magento_Customer/js/customer-data'
], function ($, modal, loader, customerData) {
    'use strict';
 
    return function(config, node) {
 
        var product_id = jQuery(node).data('id');
        var product_url = jQuery(node).data('url');
 
        var options = {
            type: 'popup',
            responsive: true,
            innerScroll: false,
            title: $.mage.__('Quick View'),
            buttons: [{
                text: $.mage.__('Close'),
                class: 'close-modal',
                click: function () {
                    this.closeModal();
                }
            }]
        };
 
        var popup = modal(options, $('#quickViewContainer' + product_id));
 
        $("#quickViewButton" + product_id).on("click", function () {
            openQuickViewModal();
        });
 
        var openQuickViewModal = function () {
            var modalContainer = $("#quickViewContainer" + product_id);
            modalContainer.html(createIframe());
 
            var iframe_selector = "#iFrame" + product_id;
 
            $(iframe_selector).on("load", function () {
                modalContainer.addClass("product-quickview");
                modalContainer.modal('openModal');
                this.style.height = this.contentWindow.document.body.scrollHeight+10 + 'px';
                this.style.border = '0';
                this.style.width = '100%';
                observeAddToCart(this);
            });
        };
 
        var observeAddToCart = function (iframe) {
 
            var doc = iframe.contentWindow.document;
 
            $(doc).contents().find('#product_addtocart_form').submit(function(e) {
                e.preventDefault();
                $.ajax({
                    data: $(this).serialize(),
                    type: $(this).attr('method'),
                    url: $(this).attr('action'),
                    success: function(response) {
                        customerData.reload("cart");
                        customerData.reload("messages");
                        $(".close-modal").trigger("click");
                        $('[data-block="minicart"]').find('[data-role="dropdownDialog"]').dropdownDialog("open");
                    }
                });
            });
        };
 
        var createIframe = function () {
            return $('<iframe />', {
                id: 'iFrame' + product_id,
                src: product_url + "?iframe=1"
            });
        }
    };
});

我们的想法是使用Magento的默认模式窗口,用前面添加的按钮打开它,创建iframe,在iframe中加载产品页面,最重要的是监听加入购物车表单的提交事件,以便于我们可以在添加产品后关闭窗口。