2

I'm basically looking for a more up-to-date way to do this: https://www.vaersaagod.no/en/multi-attribute-variant-selection-in-craft-commerce

So that I can allow users to select color and size in two separate steps, like Tailwind UI.

Tailwind UI Add to Cart

Does anyone have a guide / examples of how to do this?

1 Answer 1

1

Ended up going with Sprig, which seems to work pretty well. Open to ideas on how to improve this, especially if there's some better options for performance.

{% set colour = colour ?? '' %}
{% set addedToCart = success is defined %}
{% set variants = craft.variants().productId(productId).relatedTo(colour).all() %}
{% set colours = craft.categories().group('colours').all() %}

<form sprig s-method="post" s-action="commerce/cart/update-cart">
  <input type="hidden" name="qty" value="1">
  <fieldset>
    <legend>Colour</legend>
    <div>
      {% for colourOption in colours %}
        <label>
          <input sprig type="radio" name="colour" value="{{ colourOption.id }}">
          <p id="colour-label" class="sr-only">
            {{ colourOption.title }}
          </p>
          <span class="h-8 w-8 bg-{{ colourOption.slug }}-500 border-gray-200 rounded-full p-2 {{ colour == colourOption.id ? "ring-4 ring-gold-500" : "ring-2 ring-gray-200" }}"></span>
        </label>
      {% endfor %}
    </div>
  </fieldset>
  <fieldset class="mb-8">
    <legend>
      Size
    </legend>
    <div>
    {% for variant in variants %}
      <label>
        <input type="radio" name="purchasableId" value="{{ variant.id }}">
        {{ variant.title }}
      </label>
    {% endfor %}
  </fieldset>

  <button type="submit">Add to cart</button>
  
  {% if addedToCart and success %}
    <div>{{ product.title }}</span> was added to your cart!</div>
  {% endif %}
</form>
2
  • Interested to see this, and am considering re-doing our variatn order forms with a similar approach. I can't see Sprig being any much different, performance wise, than anything else really - ultimately it's an ajax call to the same controller and it's really the Commerce time here that is the determining factor, I think? The only time Sprig can distinctly slow things down is if you're repeatedly hitting the server when you could instead be doing something simply on the client side (e.g. sorting and filtering, for example). Dec 2, 2021 at 0:01
  • Yeah basically what I thought. It's working well in practice!
    – supazu
    Dec 7, 2021 at 3:18

Your Answer

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

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