Conversations about creating, managing, and using metafields to store and retrieve custom data for apps and themes.
I have a metaobject called "color" with these fields:
color.name (single text)
color.hexcode (color)
color.image (file)
I created a product metafield called product.metafields.custom.color_filter_swatch that has a content type set as the "color" metaobject and multiple entries.
From my product page I want to access the hexcolor values that the product has associated with it through the color_filter_swatch metafield (that points to the color metaobject). However I cannot find the correct syntax.
I tried debugging it by displaying liquid variables in the html and this input:
{% if product.metafields.custom.color_filter_swatch != blank %} <p>Metafield is not blank.</p> {% assign color_metaobjects = product.metafields.custom.color_filter_swatch.value %} <p>Color Metaobjects: {{ color_metaobjects | json }}</p> <p>[0]: {{ color_metaobjects[0] | json }}</p> <p>size: {{ color_metaobjects | size }}</p> <p>color_filter_swatch size: {{ product.metafields.custom.color_filter_swatch | size }}</p> {% else %} <p>No color swatches assigned.</p> {% endif %}
is giving me this output:
Metafield is not blank.
Color Metaobjects: [{"hexcode":"#be0000","name":"Red"},{"hexcode":"#737373","name":"Grey"},{"hexcode":"#ffffff","name":"White"},{"hexcode":"#000000","name":"Black"}]
[0]: null
size: 0
color_filter_swatch size: 0
Which I find rather weird. The color_metaobjects variable is displayed as an array of objects, but when I try to access its elements it behaves as if it wasn't an array ( color_metaobjects[0] is null and color_metaobjects.size is 0). I also tried to access it using color_metaobjects[0].value but it's also null.
What could I be missing here?
Thanks in advance, any help would be very much appreciated.
Hi @felipelf00
Please try to update like below:
{% if product.metafields.custom.color_filter_swatch != blank %}
<p>Metafield is not blank</p>
{% assign color_metaobjects = product.metafields.custom.color_filter_swatch.value %}
{% for color_metaobject in color_metaobjects %}
<p>Name: {{ color_metaobject.name }}</p>
<p>Hexcode: {{ color_metaobject.hexcode }}</p>
<p>Image: <img src="{{ color_metaobject.image | image_url: width: '200' }}" /></p>
{% endfor %}
{% else %}
<p>No color swatches assigned.</p>
{% endif %}
Hope this helps!
Thanks for your reply. I ended up finding a solution, but it's similar to what you suggested.
Basically to access a value that is in a list, you must iterate throught that list (syntax such as color_metaobject[0] does not work).
This worked for me:
{% for item in product.metafields.custom.color_filter_swatch.value %} <p>item.hexcode: {{ item.hexcode }}</p> {% endfor %}
This video also helped me clarify the different syntaxes for each type of metafield: