Forum for discussing general topics related to Couch.
3 posts Page 1 of 1
Is there a way to link a variable to a different product image?

Example:
There is the same shirt but with many different colors and I want to add product images for all of them.

Ideally when I click the variable in the product page the image can change but I know this can be done with js.

I'm pretty new with the cart functionality so any help would be appreciated.
Thanks
There is no direct way of linking a variant with an image (or any other additional info).
However, I think, this can be done in an indirect manner.

For example, we can define a repeatable region with a type 'image' and a type 'text' region and input into it the images and the variant names (e.g. Red, Black etc.) -
Code: Select all
<cms:repeatable name='variant_images' label='Variant Images'>
    <cms:editable type='text' name='variant_name' label='Variant Name' />
    <cms:editable type='image' name='variant_image' label='Image' show_preview='1' preview_width='100' />
</cms:repeatable>

If care is taken to input the same names for the variants as those used while defining them, it should now be possible on the frontend to use some JS to tie up the product variant dropdowns/radio_buttons with the info inputted above.

To do that, it'd be useful to have the info in a form that is JS amenable. We could use this to convert it into a JSON object with variant_names as keys and images as their values -
Code: Select all
<cms:set arr_images='[]' is_json='1' scope='global' />
<cms:show_repeatable 'variant_images'>
    <cms:put "arr_images.<cms:show variant_name />" variant_image scope='global' />
</cms:show_repeatable>

Now from within JS, we can use it, e.g., as follows -
Code: Select all
<script>
    var my_images = <cms:show arr_images as_json='1' />;
    console.log( my_images );
</script>

Output -
Code: Select all
{
   "Red":"http:\/\/localhost\/myuploads\/image\/600\/PLBCvuEbCq.jpg",
   "Black":"http:\/\/localhost\/myuploads\/image\/600\/weyamle9fdm-u.jpg",
   "Green":"http:\/\/localhost\/myuploads\/image\/600\/Haz8prUXrI4-uns.jpg"
}

I am sure you can take it from here.

Hope this helps
If you prefer associative arrays in JS with 'labels', then Repeatables natively can be used in JSON without much hassle -

Code: Select all
<script>
    var my_images = <cms:show_repeatable 'variant_images' as_json='1' />;
    console.log( my_images );
</script>


Output -
Code: Select all
{
   "variant_name" : "Red", "variant_image" : "http:\/\/localhost\/myuploads\/image\/1.jpg",
   "variant_name" : "Black", "variant_image" : "http:\/\/localhost\/myuploads\/image\/2.jpg"
}
3 posts Page 1 of 1