Shopware6已添加错误无法移除:购物车错误未清除问题排查
解决Shopware6购物车错误无法移除的问题
问题根源分析
你的代码存在三个核心问题导致错误无法正确移除:
- 移除错误的逻辑判断完全错误(误判为
promotion-not-found) - 物理产品状态判断方式错误(直接索引访问集合对象)
- 未同步清理验证器的
ErrorCollection和购物车自身的错误集合
修复后的完整代码
class MinimumOrderValueValidator implements CartValidatorInterface { private $config; public function __construct(SystemConfigService $config) { $this->config = $config; } public function validate(Cart $cart, ErrorCollection $errorCollection, SalesChannelContext $context): void { $hasPhysicalProduct = $this->hasPhysicalProduct($cart); $errorId = 'minimum_order_value_error'; if (!$hasPhysicalProduct) { $this->removeMinimumOrderValidationError($cart, $errorCollection, $errorId); return; } $minimumOrderValue = (float)($this->config->get('MyAppTheme.config.MinimumOrderValue') ?? 10); if ($cart->getPrice()->getTotalPrice() < $minimumOrderValue) { // 检查错误是否已存在于任一集合中 $existingError = $errorCollection->get($errorId) ?? $cart->getErrors()->get($errorId); if (!$existingError) { $errorCollection->add(new MinimumOrderValueNotReachedException( $errorId, (string)$minimumOrderValue )); } } else { $this->removeMinimumOrderValidationError($cart, $errorCollection, $errorId); } } private function hasPhysicalProduct(Cart $cart): bool { foreach ($cart->getLineItems() as $item) { // 使用StateCollection的has方法判断物理产品状态 if ($item->getStates()->has('is-physical')) { return true; } } return false; } private function removeMinimumOrderValidationError(Cart $cart, ErrorCollection $errorCollection, string $errorId): void { // 同时清理验证器错误集合和购物车错误集合 $errorCollection->remove($errorId); $cart->getErrors()->remove($errorId); } }
关键修改说明
修正物理产品判断逻辑
替换了原代码中直接索引访问StateCollection的错误方式,使用集合原生的has()方法判断是否存在is-physical状态,确保逻辑准确。修复错误移除逻辑
- 删除了错误的
promotion-not-found判断条件,改为直接通过错误ID移除目标错误 - 新增对验证器
$errorCollection的清理——Shopware每次验证会重新初始化该集合,需确保本次验证不会残留旧错误 - 同步清理
$cart->getErrors()——模板渲染的购物车错误来自该集合,必须手动移除才能让错误从前端消失
- 删除了错误的
优化错误存在性检查
同时检查$errorCollection和$cart->getErrors()中的错误,避免重复添加相同错误。
内容的提问来源于stack exchange,提问作者Amir Dora.
相关产品推荐
相关产品推荐

