我正在尝试将过滤器添加到类别页面上的产品集合中。

我想创建一个观察者,该观察者侦听到Catalog_Product_Collection_Load_Before,但我发现偶数在 changelog

如何在没有此观察者的情况下过滤产品集合。我应该使用插件吗?在哪里开始?

有帮助吗?

解决方案

好吧,我确实基于这个问题。如果其他人面临这个问题,那么去的方法确实是创建一个插件。

创建文件frontend / di.xml:

<?xml version="1.0"?>
<!--
/**
 * Copyright © 2015 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <type name="Magento\Catalog\Model\ResourceModel\Product\Collection">
        <plugin name="sidebarFilters" type="Sebwite\Sidebar\Model\Plugin\SidebarFilter"/>
    </type>
</config>
.

然后创建插件:

<?php namespace Sebwite\Sidebar\Model\Plugin;

use Magento\Catalog\Model\ResourceModel\Product\Collection as ProductCollection;

class SidebarFilter
{
    /**
     * aroundAddFieldToFilter method
     *
     * @param \Magento\Catalog\Model\ResourceModel\Product\Collection $collection
     * @param \Closure                                                $proceed
     * @param                                                         $fields
     * @param null                                                    $condition
     *
     * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
     */
    public function aroundAddFieldToFilter(ProductCollection $collection, \Closure $proceed, $fields, $condition = null)
    {
        // Here we can modify the collection

        return $fields ? $proceed($fields, $condition) : $collection;
    }
}
.

许可以下: CC-BY-SA归因
scroll top