0

I am using Craft Commerce with Sprig and I am hoping to get some help with the add to cart button, which I need to change dynamically dependent on what is already in the cart.

Essentially I have two variants per product - a free sample and a 1 metre squared piece of material which is a paid for product.

Customers are only allowed to add 1 of the same product to the cart, so I also want to look at the cart items, to see whether the variant id is already in the cart. If so, the button changes to 'View Cart' or something similar.

It works fine with a simple product using product.id (see code below) however I am struggling to get it working with variants.

Any help would be greatly appreciated.

{% if cart is not defined %}
{% set cart = craft.commerce.carts.cart %}
{% endif %}

{% set addedToCart = success is defined %}

{% set variantId = craft.app.request.getQueryParam('id') %}

{% set myVariantQuery = craft.variants()
    .id(variantId) %}

{% set variant = myVariantQuery.one() %}

{% set product = craft.products.id(productId).one() %}

{% set cartProductIds = [] %}
{% set cartVariantIds = [] %}

{% for item in cart.lineItems %}
{% set cartProductIds = cartProductIds|merge([item.purchasable.product.id]) %}
{% endfor %}

<form sprig s-method="post" s-action="commerce/cart/update-cart" class="mt-4">

    {% set purchasableId = purchasableId ?? null %}

    <select sprig name="purchasableId" class="w-full">
        {% for variant in product.variants %}
            <option value="{{ variant.id }}" {{ purchasableId == variant.id ? 'selected' }}>{{ variant.title }} - {{ variant.id }} - £{{variant.price}}</option>
        {% endfor %}
    </select>

{% if product.id in cartProductIds %}


<a href="/shop/cart" class="w-full m-0 cursor-pointer px-4 py-4 inline-block bg-pink hover:bg-gray-100 text-white hover:text-pink text-base text-center mt-2">
VIEW BASKET
</a>

{% else %}

<button type="submit" class="w-full m-0 cursor-pointer px-4 py-4 inline-block bg-pink hover:bg-gray-100 text-white hover:text-pink text-base text-center mt-2">
ADD FREE SAMPLE TO BASKET
</button>
     
{% endif %}

    </form>



{% if addedToCart %}
    <script>
        // document.getElementById('cart').dispatchEvent(new Event('refresh'));
        htmx.trigger(htmx.find('#cart-total'), 'refresh');
    </script>
{% endif %}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.