Shopware:有条件地取消将产品添加到购物车

gik*_*res 3 shopware shopware6 shopware6-api

我想实现一个进行外部 API 调用的功能,然后根据请求是否满足将产品线项目添加到购物车,否则它会向客户显示一条翻译后的闪存消息,表明无法添加产品出于 X 个原因加入购物车。

我尝试过的是订阅,BeforeLineItemAddedEvent但此时该订单项似乎已添加到购物车中,我不太确定如何实现闪存消息。

dne*_*adt 8

您可以实现自己的自定义购物车验证器。如果您的验证标准基于对外部资源的请求,请注意每次构建购物车时都会调用此验证器。也许考虑缓存这些请求。

服务定义:

<service id="MyPlugin\Core\Checkout\Cart\LineItem\CustomValidator">
    <tag name="shopware.cart.validator"/>
</service>
Run Code Online (Sandbox Code Playgroud)

验证器类:

class CustomValidator implements CartValidatorInterface
{
    public function validate(Cart $cart, ErrorCollection $errors, SalesChannelContext $context): void
    {
        foreach ($cart->getLineItems()->getFlat() as $lineItem) {
            // your custom logic here
            if ($lineItem->getLabel() === 'Aerodynamic Concrete Isoswitch') {
                $errors->add(new IncompleteLineItemError($lineItem->getId(), 'yourCustomSnippet'));
                $cart->getLineItems()->removeElement($lineItem);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您可能想要实现自己的自定义扩展,Error而不是使用此处预先存在的扩展IncompleteLineItemError

您翻译的消息 json:

{
  // storefront.en-GB.json
  "checkout": {
    "yourCustomSnippet": "This is not allowed"
  }
}
Run Code Online (Sandbox Code Playgroud)

您可以在文档中找到更详细的解释。