Search code examples
phpshopwareshopware6

Remove item from cart during CartChangedEvent in Shopware (PHP)


I am trying to remove a LineItem from the cart during the CartChangedEvent but it does not work. I tried

public function cartChangedEvent(CartChangedEvent $pEvent)
{
    $lineItems = $pEvent->getCart()->getLineItems();
    $x = $lineItems->count();
    $lineItems->removeElement($pEvent->getCart()->getLineItems()->first());
    $lineItems->count(); // The size is $x - 1 now
    $pEvent->getCart()->setLineItems($lineItems);
}

But that does not work. The line items list gets changed, but the cart does not change even though I am using setLineItems


Solution

  • The cart needs to be persisted to be saved. To do that you have to add:

    <argument type="service" id="Shopware\Core\Checkout\Cart\CartPersister"/>
    

    To your service in the service.xml to receive a CartPersister. After you changed the line items you have to call save(Cart $cart, SalesChannelContext $context) on the CartPersister.