3

How do you reset or empty the cart, in Commerce 2? There is no mention of this in the documentation.

In Commerce 1, it was possible to issue a request to the commerce/cart/removeAllLineItems action to clear the cart, but this no longer works.

2 Answers 2

5

The commerce/cart/remove-all-line-items action (or in Craft 2 terms, commerce/cart/removeAllLineItems) was deprecated (and subsequently removed in Commerce 3), so it's up to you to build a form to explicitly delete all line items:

<form method="post">
    {{ csrfInput() }}
    {{ actionInput('commerce/cart/update-cart') }}

    {% for lineItem in craft.commerce.carts.cart.lineItems %}
        <input type="hidden" name="lineItems[{{ lineItem.id }}][remove]" value="✓">
    {% endfor %}

    <button type="submit">Empty Cart</button>
</form>

This snippet just loops over the current line items, and outputs a hidden input element, which sends the proper POST value to the update-cart action.

It's also possible to give your customer control over which line items are to be removed by changing the input to a check-box (and providing adequate labeling).

3
  • Has The commerce/cart/remove-all-line-items changed? I get this "Unable to resolve the request: commerce/cart/remove-all-line-items" when I try to empty my cart. This worked previously for me, but not anymore. Commented May 8, 2020 at 17:53
  • I think your answer at the beginning of the reply! This action was deprecated, and appears to have been completely removed in Commerce 3. You should be able to use the provided snippet with the consolidated update-card action. Commented May 9, 2020 at 2:15
  • Awe, I read that as the craft2 was deprecated, which I was aware of, didn't realize the first was as well. Commented May 12, 2020 at 14:36
6

Depending on context, here's another handy way of clearing the cart for Commerce 2/3

In a template, you can put:

{% do cart.setLineItems([]) %}
{% do craft.app.elements.saveElement(cart) %}

You could e.g. just use a direct link to a template that does that, and in turn re-directs to wherever...if you don't want to muck around with a form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.