1

I'm trying to add a product to a cart (and emptying the cart first) if a user just visits a template. My goal is to make a one-page checkout: so I want the address info on the product page itself. This is what I have so far. I thought the first line would make a cart if there is no cart yet, but it seems nothing happens. (cart.id = null)

{% set cart = craft.commerce.carts.cart %}
Cart ID is {{ cart.id }}
{% do cart.setLineItems([]) %}
{% set lineItem = craft.commerce.lineitems.resolveLineItem(cart.id, product.id, [], 1, '') %}
{% do cart.addLineItem(lineItem) %}
1

I tried this myself and it threw an error when there was no cart attached to the session.

I then found these two lines of code in the Craft Commerce CartController.php:

        // Get the cart from the current users session, or return a new cart attached to the session
        $cart = Plugin::getInstance()->getCarts()->getCart(true);

getCart() can be found in the Carts Service

Which lead me to try:

{% set cart = craft.commerce.carts.cart(true) %}

So if you pass in true, you force it to save the cart and thus you seem to be able to create a new (empty) cart.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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