1

So this may be a stupid question, but I've sort of never wrapped my head around it. When fetching an image from an entry -- even if there's only one associated with the field -- you can't just do:

{% set image = entry.image %}

You have to say:

{% set image = entry.image.first() %}

Which implies that the returned data are an object or array, and that the actual desired image is the "first" item in it. My questions are:

  1. Why is it structured this way?
  2. Which other properties are in the entry.image apart from the actual resource itself? What would you use those for?

I realize this may be obvious to pro Craft developers, but I remember the first Craft site I ever built, I had a devil of a time trying to remember that!

1

When you reference a relationship field (ie: Entries field, Assets field, etc), you will automatically get an ElementCriteriaModel to represent the "value" of that field.

Since entry.image is giving you an ElementCriteriaModel, you need to specify exactly what you want that ECM to do. If you try to use the ECM without specifying .first (or .last, or .total), then by default it will assume you meant .find. Which is obviously not what you're trying to do in this case.

I highly recommend reading my answer on this other thread... It's not quite a duplicate of your question, but it covers a lot of the same ground.

  • Ah OK, that's making more sense, and thank you for the link to your other answer. So when creating fields for a section, is every 'asset' field a 'relationship' field? I know as a field 'entries' would be, but I didn't realize the same would be true for images/assets. Does that then imply the other fields, like 'plain text' and 'light switch' are not relationships? Follow-up Q: Of all the possible fields to associate with a section, which are which? Thank you! – Nathan D Huening Feb 9 '17 at 21:02
  • Relationship fields are any fields based on elements... I'd recommend reading up on Element Types, as they're a pretty crucial part of the Craft ecosystem. – Lindsey D Feb 9 '17 at 21:30

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.