2

I'm working with Craft Commerce with a set of individual items in a product type and in another, I have packaged sets of the same. The sets (cardSets) have a relation field to select the required individual cards. The code is in the product entry template for the individual card and my intention is to highlight that the single card can be purchased in a set.

I'm using the following code to do a simple reverse relationship but I can't get this to work and I'm not sure if I've got the syntax correct. I'm not seeing any return or error. How do I know if I'm getting an object back?

{% set relatedProduct = craft.commerce.products({
    type: 'cardSets',
    relatedTo: {
        targetElement: product,
        field: 'productsInSet'
        }
}) %}

{{ relatedProduct.title }}

1 Answer 1

2

When you use the craft.commerce.products tag, it will return a criteria model, but you are treating it as the first result by accessing the title attribute.

Try {{ relatedProduct.first().title }} instead.

4
  • You should always check if first() actually returns something before accessing properties or methods of the element model.
    – carlcs
    Commented Sep 30, 2016 at 9:38
  • Thanks so much stephen & @carlcs. Looks like I heed to swat-up on the models
    – Britchie
    Commented Sep 30, 2016 at 15:57
  • Also, with the way I have the entries set-up presently, there will only ever be a single relationship returned. Is it possible to add the .first() to the main query instead of for every property? (couldn't find an example)
    – Britchie
    Commented Sep 30, 2016 at 16:43
  • @Britchie Exactly as you say, see here: craftcms.stackexchange.com/questions/289/… Commented Oct 3, 2016 at 10:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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