Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 61 ยท Cart, Checkout and Customer Pages

The Product Form and Add to Cart

Build the Shopify product form: the form tag, variant id and quantity inputs, line item properties, selling plans, no-JavaScript fallback and dynamic checkout buttons.

The product form is where browsing turns into buying. It is small: a variant id, a quantity and a button. Yet almost every other part of the product page exists to fill this form correctly, and it must work even if your JavaScript never loads. Shopify's cart accepts a plain HTML form post, which is why a theme with no scripts at all can still sell.

This lesson shows the form tag, the inputs that matter (variant id, quantity, line item properties, selling plan), what the browser sends, the no-JavaScript behavior and the dynamic checkout buttons. A runnable stand-in models how the cart treats a submission. It comes after Building the Product Page and Variants and Option Pickers, and prepares The Ajax Cart API, which sends the same data with fetch.

The form tag, /cart/add and the cart exist only on a real store, so the theme code is read-only and targets current Online Store 2.0 themes. The live examples are a stand-in cart written in JavaScript: it shows the rules (merge lines, hidden properties, validation) but is not Shopify's implementation, and prices are made-up.

The form tag

LIQUID
{%- form 'product', product, id: form_id, class: 'product-form', novalidate: 'novalidate' -%}
  <input type="hidden" name="id" value="{{ product.selected_or_first_available_variant.id }}">

  <label for="qty-{{ section.id }}">Quantity</label>
  <input id="qty-{{ section.id }}" type="number" name="quantity" value="1" min="1">

  <button type="submit" name="add"
    {% unless product.selected_or_first_available_variant.available %}disabled{% endunless %}>
    {%- if product.selected_or_first_available_variant.available -%}
      {{ 'products.product.add_to_cart' | t }}
    {%- else -%}
      {{ 'products.product.sold_out' | t }}
    {%- endif -%}
  </button>
{%- endform -%}

{% form 'product', product %} outputs a <form> element whose action is the cart add URL (/cart/add) and whose method is post. It also adds hidden fields Shopify uses, so you should never write the <form> tag by hand. The optional arguments set the element's id, class and other attributes. After the tag you provide the fields that matter:

Field name Required Meaning
id yes the variant id to add (not the product id)
quantity no, defaults to 1 how many to add
properties[Name] no a custom detail attached to this line
selling_plan no the subscription or pre-order plan id
return_to no where to go after a non-JavaScript submit

The most common mistake is posting the product id. The cart works in variants, so id must be a variant id, and your option picker has to update that hidden input whenever the shopper chooses a different combination.

If a product has several variants, never leave id empty or fixed to the first one. If the picker JavaScript fails, a stale variant id silently buys the wrong size. Render the selected variant id on the server and update it in JavaScript only as an enhancement.

The id input and variant pickers

A product with one variant (the "Default Title" product) needs no picker. For others, there are two common setups: a <select name="id"> listing every variant with its availability, or radio groups for each option that JavaScript maps to the matching variant. The select version works without JavaScript, which makes it the best baseline. Radio pickers need script to find the variant, as in the earlier lesson.

Line item properties

A line item property is extra information attached to one cart line: an engraving text, a gift message, a chosen font. Add an input whose name is properties[Label]:

LIQUID
<label for="engrave">Engraving (optional)</label>
<input id="engrave" name="properties[Engraving]" type="text" maxlength="20">

Rules to remember:

  • The label inside the brackets is shown to the shopper in the cart and at checkout, and appears in the order for fulfillment.
  • Properties whose name begins with an underscore, such as _source, are not shown in the cart or checkout, so you can use them for internal tracking.
  • An empty property is dropped, so an optional blank engraving field does not create noise on the order.
  • Two lines with the same variant but different properties are separate lines: a mug engraved "Ann" and one engraved "Bo" must not be merged.
  • Properties are text typed by the shopper, so treat them as untrusted when you print them back (the cart template escapes when you use | escape).

Selling plans

When an app adds subscriptions or pre-orders to a product, the product has selling plan groups, and each plan has an id. To buy through a plan, post selling_plan with that id:

LIQUID
{%- if product.selling_plan_groups.size > 0 -%}
  <fieldset>
    <legend>Purchase options</legend>
    <label><input type="radio" name="selling_plan" value="" checked> One-time purchase</label>
    {%- for group in product.selling_plan_groups -%}
      {%- for plan in group.selling_plans -%}
        <label><input type="radio" name="selling_plan" value="{{ plan.id }}"> {{ plan.name }}</label>
      {%- endfor -%}
    {%- endfor -%}
  </fieldset>
{%- endif -%}

An empty value means a normal purchase. Plans can change the price, which you read from the variant's selling_plan_allocations. Subscription billing and its lifecycle belong to the app and to general e-commerce rules: see Pricing Models for the concepts.

What happens on submit

Without JavaScript, the browser posts the form to /cart/add. Shopify adds the item to the cart, then redirects to the cart page, unless a return_to field says otherwise (for example return_to with the value back, or /checkout). If the variant is sold out or the quantity exceeds what is available, Shopify shows an error page or message instead.

sequenceDiagram
  participant B as Browser
  participant S as Shopify
  B->>S: POST /cart/add (id, quantity, properties)
  S->>S: validate variant and stock
  alt success
    S-->>B: 302 redirect to /cart
  else not available
    S-->>B: error page with message
  end

The plain form round trip. The Ajax version sends the same fields and gets JSON back instead of a redirect.

This is why the form must always be real HTML: it is your fallback, your SEO-safe baseline and the thing screen readers and keyboards already understand. A JavaScript enhancement can intercept the submit event, call the Ajax API, and update the page without a reload. If the script throws, the form still posts normally.

Buy buttons and dynamic checkout

Right after the form fields, themes often add:

LIQUID
{{ form | payment_button }}

The payment_button filter outputs the dynamic checkout buttons: the store's accelerated checkout options such as Shop Pay, Apple Pay or Google Pay, chosen automatically by what the shopper's device supports and what the store has enabled. Details to know:

  • The merchant controls whether they show (in the payments settings); the Liquid just asks for them.
  • They skip the cart and go straight to checkout with the selected variant, so keep them next to the add-to-cart button, not hidden below.
  • They are rendered by Shopify and styled with limited options, so do not rely on pixel-perfect control.
  • Pair them with a quantity input in the same form, since the filter reads the form's fields.

There are also cart permalinks such as /cart/12345:2, which add variant 12345 with quantity 2 and send the shopper on. They are handy for email links and "buy again" buttons. For how a full checkout is structured in general, see Checkout Flow.

Stand-in: how a cart treats submissions

Shopify merges identical lines, keeps different properties apart, hides underscore properties and rejects invalid input. This stand-in models those rules with a small cart object so you can try form data without a store.

JS Stand-in: a cart that handles form submissions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that the first and third attempts merge into one line of 2, while the "Bo" engraving gets its own line. The _source property is stored but not displayed.

Stand-in: building the request body

On submit, the browser encodes the form fields in a fixed way. The JavaScript FormData API does the same thing, which is what you use for the Ajax version. This stand-in shows the encoded body for a form with properties, a selling plan and special characters, so you can see why properties[Engraving] is the field name and how values are escaped.

JS Stand-in: what the browser sends

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The ampersand in "Ana & Rui" travels as %26, so it cannot split the field. This is also why you should build the Ajax request from the form itself (new FormData(form)) rather than concatenating strings.

Practical checklist

  • Always render the form on the server with a valid variant id selected.
  • Disable the button, with a label, when the variant is unavailable.
  • Give inputs real labels, and a visible, announced error for failed adds (see Accessibility in Themes).
  • Cap property length with maxlength and validate on your side, as the server accepts what it is given.
  • Test with JavaScript disabled, and with the theme editor's preview.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which id must the hidden input named id contain in the product form?

    The cart is made of variants, so the form posts the id of the selected variant.
  2. 2. How do you attach an engraving text to a cart line?

    Line item properties use the properties[Label] naming pattern, and the label is shown in the cart and order.
  3. 3. A property is named _source. What happens to it?

    Names starting with an underscore are hidden from the shopper, which suits internal tracking values.
  4. 4. What does the plain form do when JavaScript is disabled?

    The form is a normal HTML post, so the cart works without scripts. return_to can change the destination.
  5. 5. Two lines have the same variant but different engraving texts. How does the cart treat them?

    Lines with different properties are different lines, so each engraving is fulfilled correctly.

Summary

  • Use {% form 'product', product %} and post a variant id, an optional quantity, properties[Label] and selling_plan.
  • The server-rendered form is your baseline: it works without JavaScript and redirects to the cart (or to return_to).
  • Empty properties are dropped, underscore properties are hidden, and different properties make separate lines.
  • payment_button adds dynamic checkout buttons controlled by the merchant's payment settings.
  • Validate, label and error-handle the form as carefully as any other form.

Next, send the same data without a page reload in The Ajax Cart API.