英文:
Shopware 6 - How to save something in the cart?
问题
我希望我可以帮助您解决Shopware 6中关于保存购物车中已删除商品的问题。
在我的当前实现中,我正在使用CartProcessorInterface并在collect函数中添加行项目。然而,我遇到了一个问题,即如果用户从购物车中删除这些商品,它们将在页面重新加载或购物车重新加载后再次添加。
我渴望找到一个解决方案,以防止用户删除这些商品后再次添加它们。是否有一种方法或方法来存储已从购物车中删除的商品信息,以防止其再次添加?
非常感谢您的帮助!
英文:
I hope I can assist you with the issue you're facing in Shopware 6 regarding saving removed items in the cart.
In my current implementation, I'm using the CartProcessorInterface and adding line items in the collect function. However, I've encountered an issue where if the user removes these items from the cart, they are re-added upon page reload or cart reload.
I'm eager to find a solution to prevent these items from being added again after the user has removed them. Is there a method or approach to store the information that an item has been removed from the cart and should not be added again?
Thank you in advance for your help!
答案1
得分: 6
你不应该在处理器中添加订单项,例如,在事件订阅器中执行此操作,然后通过购物车服务添加它们。
请查看官方文档:
https://developer.shopware.com/docs/guides/plugins/plugins/checkout/cart/add-cart-items
// Shopware\Core\Checkout\Cart\LineItemFactoryRegistry
$lineItem = $this->factory->create([
'type' => LineItem::PRODUCT_LINE_ITEM_TYPE, // 结果为 'product'
'referencedId' => 'myExampleId', // 这不是有效的 UUID,请更改为您的实际 ID!
'quantity' => 5,
'payload' => ['key' => 'value']
], $context);
// Shopware\Core\Checkout\Cart\SalesChannel\CartService
$this->cartService->add($cart, $lineItem, $context);
如果需要在删除另一个订单项时对订单项执行某些操作,您可以使用 BeforeLineItemRemovedEvent 或 AfterLineItemRemovedEvent。
英文:
You shouldn't add line items in the processors, do that for eg. in an event subscriber and add them via the cart service.
Take a look at the official documentation:
https://developer.shopware.com/docs/guides/plugins/plugins/checkout/cart/add-cart-items
// Shopware\Core\Checkout\Cart\LineItemFactoryRegistry
$lineItem = $this->factory->create([
'type' => LineItem::PRODUCT_LINE_ITEM_TYPE, // Results in 'product'
'referencedId' => 'myExampleId', // this is not a valid UUID, change this to your actual ID!
'quantity' => 5,
'payload' => ['key' => 'value']
], $context);
// Shopware\Core\Checkout\Cart\SalesChannel\CartService
$this->cartService->add($cart, $lineItem, $context);
And if you need to do something to a line item when another is removed you can use the BeforeLineItemRemovedEvent or AfterLineItemRemovedEvent
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论