Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
446 views
in Technique[技术] by (71.8m points)

javascript - Unable to pass variant data into shopify form

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. enter image description here

But i need the data to bee accessible on the form like so;

enter image description here

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 %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 %}

code image


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...