Reputation: 149
I am trying to pass through variant JSON data using a data-variants attribute into an add to cart form, but i cant refactor correctly to work with Shopifys more up to date form syntax.
<form id="add-to-cart-form" action="/cart/add" method="post" enctype="multipart/form-data" data-variants="{{variants_with_quantity_json | url_param_escape }}"></form>
{% form 'product', product, data-product-form: '', data-product-handle: product.handle, data-enable-history-state: 'true', id: "add-to-cart-form" %}
The data variant attribute simply outputs the object with no data in my version.
But i need the data to bee accessible on the form like so;
I am trying to add the invetory qty to the product.variants.json and need to figure out how {{ variants_with_quantity_json }} can be passed to the form.
{% assign variants_with_quantity_json = product.variants | json %}
{% unless variants_with_quantity_json contains 'inventory_quantity' %}
{% for variant in product.variants %}
{% assign replace_hook_variant_id = '"id":' | append:variant.id %}
{% assign replace_id_plus_inventory = replace_hook_variant_id | append: ',' | append: '"inventory_quantity":' |
append: variant.inventory_quantity %}
{% assign variants_with_quantity_json = variants_with_quantity_json | replace: replace_hook_variant_id,
replace_id_plus_inventory %}
{% endfor %}
{% endunless %}
Upvotes: 0
Views: 1066
Reputation: 2584
okay, you need to assign the data to a variable before pass it to {% form %}
in Shopify
So you {% form %}
look like this:
{% assign data_variants = variants_with_quantity_json | url_param_escape %}
{% form 'product', product, data-product-form: '', data-product-handle: product.handle, data-enable-history-state: 'true', id: "add-to-cart-form" data-variants: data_variants %}
or you may use the {% capture %}
liquid code tag to get and pass the value
{% capture 'data_variants' %}variants_with_quantity_json | url_param_escape{% endcapture %}
{% form 'product', product, data-variants: data_variants %}
...
{% endform %}
Upvotes: 1