Shopware6如何将变体商品作为子项归入LineItems中的父商品下
Shopware 6购物车变体商品分组展示实现方案
需求背景
要在Shopware 6中实现同父商品下的变体商品在购物车内统一分组展示的效果,目标效果如下:
但Shopware 6默认变体商品在购物车中是独立展示的,无法直接实现分组效果,默认表现如下:
可行实现方案
你当前选择的BeforeLineItemAddedEvent事件是合适的逻辑切入点,只需要补充变体判断、父商品关联标记逻辑,再配合前端模板分组渲染即可,完整实现步骤如下:
1. 订阅器逻辑补全
在事件回调中添加变体判断逻辑,给同组变体添加统一的分组标识存入payload,完整代码如下:
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent; use Shopware\Core\Content\Product\ProductEntity; use Symfony\Component\EventDispatcher\EventSubscriberInterface; class CartVariantGroupSubscriber implements EventSubscriberInterface { public static function getSubscribedEvents() { return [BeforeLineItemAddedEvent::class => 'onLineItemAdded']; } /** * @param BeforeLineItemAddedEvent $event * @throws \Shopware\Core\Checkout\Cart\Exception\InvalidPayloadException */ public function onLineItemAdded(BeforeLineItemAddedEvent $event) { $lineItem = $event->getLineItem(); // 仅处理商品类型的购物车条目 if ($lineItem->getType() !== 'product') { return; } /** @var ProductEntity $product */ $product = $lineItem->getPayloadValue('product'); // 判断是否为变体商品、是否存在父商品ID if (!$product || !$product->getParentId()) { return; } $parentId = $product->getParentId(); // 给当前变体添加父商品ID作为分组标识 $lineItem->setPayloadValue('variantGroupId', $parentId); // 可选扩展:同时存入父商品名称、主图等信息,方便前端分组展示直接调用 $lineItem->setPayloadValue('parentProductName', $product->getParent()?->getName() ?? $product->getName()); } }
2. 前端模板适配
修改购物车渲染模板(默认路径为storefront/page/checkout/cart/item.html.twig),遍历购物车条目时先按variantGroupId字段分组,再逐个渲染同一分组下的变体商品即可。
内容的提问来源于stack exchange,提问作者Arash Yazdani
相关产品推荐
相关产品推荐

