Av18
February 26, 2024, 10:41am
1
Hello,
I need to figure out one issue with the metafield which has value type = ‘json’.
metafield = ShopifyAPI::Metafield.new
metafield.variant_id = custom_bundle.master_variant_id
metafield.namespace = ‘custom_bundle’
metafield.key = ‘product_data’
metafield.value = child_products_data.to_json
metafield.type = ‘json’
metafield.save!
When child_products_data is empty then metafield.value set the value as .
instead of in the metafield, how can I set it completely blank.
like:
From API call I can not sent nil value for metafield.value if child_products_data is empty, because it gives error like #<ShopifyAPI::Errors::HttpResponseError: {"errors":{"value":["can’t be blank."]}.
Have any solution for this??
SBD
February 27, 2024, 12:56am
2
Hey @Av18
I looked into how the native admin handles this, and it appears metafields are simply deleted when their value is removed.
E.g. With bundle value:
With blank bundle value:
Av18
February 27, 2024, 6:19am
3
Hey @SBD
You are correct. Metafields are simply deleted when their value is removed. However, this only works for metafields that do not have a JSON type. For JSON type metafields, updating a nil value is prevented.
For example
when I update metafield.value
metafield.value = child_products_data.to_json
metafield.type = ‘json’
metafield.save!
to this metafield.value = nil
then it prevent like {"value":["can’t be blank."]}.
SBD
February 28, 2024, 5:46am
4
Hey @Av18
Thanks for the response. I just tried with a JSON field and saw the same results.
E.g. Here’s a json field
Which the API returns as:
But setting it to blank in admin (or running metafieldDelete / REST delete) clears the value:
I.e. try .delete instead of .save of a nil value.
Let me know if I’m not following
Av18
March 1, 2024, 8:58am
5
Hey @SBD
“Thank you for providing the correct solution.”
It successfully clears the values when I delete the metafield.