1

Really struggling with this (perhaps my brain is tired), but how would I get the image of a product for each entry in the cart screen in Craft Commerce?

2 Answers 2

4

This actually depends where the image is stored - if the asset (image) field is on the product, and is called myImage, then as per Brad's example you'd use:

lineitem.purchasable.product.myImage

...BUT if it's in rather a field on the variant you would instead reference it as:

lineitem.purchasable.myImage

(This is because lineitem refers to a variant....in the case of a product without variants it references the implicitly created defaultVariant).

1
  • Somehow I knew either you or Luke would correct me. :)
    – Brad Bell
    Jul 26, 2016 at 23:59
2

You'd access the product images just like you would any other Assets field in Craft.

Assuming you've already got the cart, and your Assets field is called productImages, something like this should work:

{% for item in cart.lineItems %}
    <p>SKU: {{ item.sku }}</p>

    <ul>
    {% for image in item.purchasable.product.productImages %}
        <li><img src="{{ image.url }}">
    {% endfor %}
    </ul>

{% endfor %}
6
  • Yeah, I had tried that but I get the following error. Craft\Commerce_LineItemModel and its behaviors do not have a method or closure named "productImage". I had assumed it would be as simple as fetching a normal asset, but everything I have tried fails. Jul 25, 2016 at 22:33
  • That's why I said "and your Assets field is called productImages". :) What's the name of the Assets field you're storing the product images in?
    – Brad Bell
    Jul 25, 2016 at 22:41
  • productImage. I have changed the code to reflect my asset field name. Jul 25, 2016 at 22:43
  • When I do a dump. {{ dump(item) }} I can't even see any reference to the productImage field. :-( Jul 25, 2016 at 22:51
  • Updated my answer. And actually tested it this time. :)
    – Brad Bell
    Jul 25, 2016 at 23:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.