I’m building a liquid theme section that suppose to display a list of variants. The product is configured via section settings. Each variant on the list must have a button that adds it to the cart.
I’m using liquid form tag to create an Add to cart button on each item (variant). After I click the button, I’m being redirected to the cart page, but no product has been added.
Here’s what I’ve done. In particular I created <input type="hidden" name="id" value="{{ variant.id }}" />
according to the docs and this example.
{% form 'product', section.settings.product %}
<input
type="hidden"
name="id"
value="{{ variant.id }}"
>
<input type="hidden" name="quantity" min="1" value="1">
{% render 'button', label: section.settings.button_label, button_size: 'small', linkless_type: 'submit' %}
{% endform %}
I’ve got a custom button snippet, but I put type="submit"
there.
Environment
- I’m running the theme in the dev mode locally using Shopify CLI.
- I’m checking results via template editor preview.
How I’ve tired to overcome this?
I’ve tired to pass variant.id
as well as selected_or_first_available_variant.id
to the hidden input of name="id", and it didn’t work out.
I’ve also tried replacing the form tag with just a regular HTML form with a proper method and action, and it did not work out as well.
<form method="post" action="/cart/add">
<input
type="hidden"
name="id"
value="{{ variant.id }}"
>
<input type="hidden" name="quantity" min="1" value="1">
{% render 'button', label: section.settings.button_label, button_size: 'small', linkless_type: 'submit' %}
</form>
I started thinking whether there are some limitations on using product forms like it only work on the product page, or there’s could only one product form per page? Or did I just made some rookie mistake?
2
Answers
I went through the code once again and after I took a little bit of perspective it turned out I've had yet another form tag wrapping the part of the code that I was working on.
Lesson learnt, always make user forms are not nested within each other.
In case anyone else stumble upon similar issues, I'm posting some errors I encountered:
Your code should work, but I made a few tweaks to ensure everything runs smoothly. I tested it and added a couple of improvements:
added a for loop to iterate through them.
custom_form_[product_id]_[variant_id]
. This helps avoid any potential conflicts when multiple forms are on the page and ensures that each variant form has a distinct ID.Here’s the updated version of your code: