1

I have an Asset source "Image link gallery" with two custom fields for each Asset: "image title" (text field) & "Image link" (Entries field - can link to multiple sources).

I have a Matrix block "Image link Gallery" with an Assets field "Images" which selects from this Asset source.

I want to be be able to select a bunch of images and return the image, title, and link to the entry.

{% for imageItem in block.images %}
    <a href="{{ imageItem.imageLink.uri }}">
        <img src="{{ imageItem.url }}" alt="">
        <span>{{ imageItem.imageTitle }}</span>
    </a>
{% endfor %}

This is returning all the images and titles but no links.

Where am I going wrong?

  • In dev mode, what comes up with {{dump(imageItem.imageLink)}}? – Aaron Berkowitz Mar 4 '15 at 4:49
2

You said it yourself, the problem is that an Entries field can link to multiple targets. So it is an array of Entry Models you're given here, or more correctly, an ElementCriteriaModel.

To get the first linked entry's Url, all you have to change is to add the first method.

<a href="{{ imageItem.imageLink.first().url }}">

But you said multiple links are allowed, so to show them all go through them in a loop.

{% for imageItem in block.images %}
    {% for linkedEntry in imageItem.imageLink %}
        <a href="{{ linkedEntry.url }}">
            <img src="{{ imageItem.url }}" alt="">
            <span>{{ imageItem.imageTitle }}</span>
        </a>
    {% endfor %}
{% endfor %}
  • Perfect. This is my first Craft site and first time with Twig. I'm still finding my way around. Thanks. – Tim Print Mar 4 '15 at 9:56
  • One more thing, @TimPrint. I'd recommend to always name an entries field handle in plural form, in you case it'd be imageLinks instead of imageLink. Entries fields always give you an ElementCriteriaModel and never a single Entry Model, even if you set the limit to 1 in the field settings. The same applies to asset fields, category fields, ... – carlcs Mar 4 '15 at 10:10
  • Anything still not working for you, Tim? – carlcs May 5 '15 at 15:25
  • Nope, all good, was just cleaning up some answers in here – Tim Print May 6 '15 at 18:54
  • Sorry! I always forget you need to click that accept button. Done. Thanks again. – Tim Print May 7 '15 at 20:16

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.