Search code examples
phpshopware6

How to effectively remove an item from the cart on shopware 6


I am trying to prevent products with different properties from been mixed up in the cart.

To do that I have set some conditions and I am displaying some notices to the user on the cart, but I need to be able to remove items that I make a notice about.

At the moment, I am setting up logic

public function onLineItemAdded(AfterLineItemAddedEvent $event): void
    {
        $lineItems = $event->getLineItems();
        $shipperExists = false;
        foreach ($lineItems as $lineItem) {
            $this->processCustomFields($lineItem);
            if (isset($lineItem->getPayload()["customFields"]["dropper_"])) {
                $shipperExists = true;
            }
        }
        if (!$shipperExists && isset($this->customFields["dropper_"])) {
            $this->flashBag->add(
                "info",
                "Invalid entry, You are trying to include a product without dropshipping option to a product with a dropshipping option."
            );         
        }
        if ($shipperExists && !isset($this->customFields["dropper_"]) && isset($this->customFields)) {
            $this->flashBag->add(
                "info",
                "Invalid entry, You are trying to include a product with dropshipping option to a product without a dropshipping option."
            );
        }
    }

and I then tried to use a cartservice.

use Shopware\Core\Checkout\Cart\CartService;

$cart = $cartService->getCart($contextToken);

$cart = $cartService->delete($cart, $lineItemId, $context);

but I am unable to delete the cart item. Please help.


Solution

  • You can use the remove method from LineItemCollection class. I did this in my Subscriber for BeforeLineItemAddedEvent and BeforeLineItemRemovedEvent.

    $cart = $event->getCart();
    $products = $cart->getLineItems();
    
    foreach ($products as $key => $product) {
        if ($yourCondition) {
            $products->remove($key);
            $cart->setLineItems($products);
        }
    }
    

    If you want to use the cartService the method is called remove as well, not delete. $identifier is the line item key, not the productId

    public function remove(Cart $cart, string $identifier, SalesChannelContext $context): Cart