You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Shopware 6中如何基于getCurrentFilter('properties')过滤ListingCriteria

Shopware 6 属性筛选逻辑修复方案

问题根源

你当前的代码逻辑失效,核心原因是事件执行顺序错误:

  • ProductListingCriteriaEvent 在商品列表查询执行前触发,用于构建查询条件
  • ProductListingResultEvent 在查询完成后触发,用于处理返回结果

所以在 ListingCriteria 方法执行时,ListingResult 方法还没运行,$currentPropertyOptions 始终是 null,自然无法基于选中属性添加过滤条件。

解决方案:直接从请求获取筛选参数

不需要通过重载页面解决,最直接的方式是从当前请求中读取用户已选中的属性筛选值,因为Shopware会将选中的属性ID通过properties参数传入请求。

修改后的订阅者代码

declare(strict_types=1);

namespace CustomFilterBasedOnSelectedOptions\Subscriber;

use Shopware\Core\Content\Product\Events\ProductListingCriteriaEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;

class Subscriber implements EventSubscriberInterface
{
    public function __construct(private readonly RequestStack $requestStack)
    {
    }

    public static function getSubscribedEvents(): array
    {
        return [
            ProductListingCriteriaEvent::class => 'ListingCriteria',
        ];
    }

    public function ListingCriteria(ProductListingCriteriaEvent $event): void
    {
        $event->getCriteria()->addAssociation('properties');
        $event->getCriteria()->addAssociation('properties.group');

        // 从当前请求中获取选中的属性筛选ID数组
        $request = $this->requestStack->getCurrentRequest();
        $currentPropertyOptions = $request?->query->get('properties', []);
        
        // 兼容非数组格式的参数
        if (!is_array($currentPropertyOptions)) {
            $currentPropertyOptions = [];
        }

        // 检查是否选中目标属性,添加自定义过滤条件
        if (in_array('c0d02d1738fd4293a489695787e06b5c', $currentPropertyOptions)) {
            $criteria = $event->getCriteria();

            $criteria->addFilter(new \Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\MultiFilter(
                \Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\MultiFilter::CONNECTION_OR,
                [
                    new \Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter('properties.name', 'Option1'),
                    new \Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\ContainsFilter('properties.name', 'Option2')
                ]
            ));
        }
    }
}

代码说明

  1. 注入 RequestStack 服务,用于获取当前请求对象
  2. 移除对 ProductListingResultEvent 的订阅,无需等待查询结果
  3. 从请求的query参数中直接读取properties值,这是Shopware属性筛选的标准参数
  4. 修正了过滤字段路径:原代码的product.properties.name错误,关联properties后直接使用properties.name即可

其他可选事件

如果需要在Shopware默认筛选逻辑执行后再调整条件,可以使用 ProductListingFilterEvent,该事件在默认筛选器应用完成后触发,适合对已有筛选逻辑进行二次修改。

内容的提问来源于stack exchange,提问作者Stacker1427

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 14:35:22