Metafields variant to update when selecting other variant

FredericVervill
Tourist
7 0 1

Hi,

 

I created a variant metafield that tell the portions of an item. It is showing in the product page, the problem is that it doesn't change when choosing another variant except when I reload the page. :

 

Video of the problem 

 

Here is the JS code I added, but it is still not working :

 

 

/**
* This callback is called whenever the variant changes and allows to update data about the active variant
*/

}, {
key: "_onVariantChanged",
value: function _onVariantChanged(previousVariant, newVariant) {
// 6th: Portions

this._updatePortions(newVariant, previousVariant); // 7th: store availability

Later on

 

 

/**
* Update the Portions
*/

}, {
key: "_updatePortions",
value: function _updatePortions(newVariant) {
if (!this.options['showPortions'] || !newVariant) {
return;
}

var productPortions = this.element.querySelector('.ProductMeta__Portions');

if (productPortions && newVariant['portions']) {
productPortions.innerText = newVariant['portions'];
}
}

Can somebody help me?

 

 

Thank you!

Frederic Verville - Floèm
Replies 2 (2)

marcoswata
Shopify Partner
122 10 36

When you debug it, does newVariant actually have a property called "portions"?

If I'm not mistaken you need to use the Storefront API to access metafields.

 

The easiest way would be adding the metafield to the variant HTML (e.g. data-portion="{{ variant.metafields.whatever.portions}}") then accessing that with Javascript by using the dataset property (e.g. variant.dataset.portion)

If my answer was helpful then please Like and Accept Solution 🙂
If you need help with design, development or marketing your store, contact me!

tim
Shopify Expert
3332 254 1201

Good points by Marco.

Obviously, variant data would not have .portions (or ['portions']) because it's pulled from the output of {{ product | json }} which does not include metafields.

You'd need to provide this data from your liquid. One way to do it is like this
(you need to provide proper namespace and key for the metafield, I've used mydata for example)
(may also need to use v.metafields.mydata.portions.value depending on how your metafields are set up).

 

 

<script>
  var portions = portions || {};
  {% for v in product.variants %}
    portions[{{ v.id }}] = {{ v.metafields.mydata.portions | json }};
  {% endfor %}
</script>

 

 

 And then in your JS code use portions[newVariant.id] instead of newVariant['portions']

If my post is helpful, consider liking it -- it will help others with similar problem to find a solution.