BoldMinded acquires Ansel, support ending for all add-ons. BoldMinded acquires Ansel, support ending for all add-ons. Read More →
Support has been discontinued. Issues remain available as an archive. Support has been discontinued. Issues remain available as an archive.
How to fetch a bunch of entries, excluding ones that don't contain images
#76 opened by jmal
Description
I'm able to loop through recent entries and spit out the first images from their galleries with relative ease. The problem is excluding the entries that don't have an image. The code:
{% set latestEvents = {
section : ['eventTypeOne', 'eventTypeTwo', 'eventTypeThree'],
order : 'eventDate asc',
eventDate : '<=' ~ now.w3cDate(),
limit : '5'
} %}
Each of these eventTypes have gallery elements with different names. I can't just hide the elements in the for loop because I need exactly 5 entries to result. This is sort of what I'm going for with no luck:
{% set latestEvents = {
section : ['eventTypeOne', 'eventTypeTwo', 'eventTypeThree'],
order : 'eventDate asc',
eventDate : '<=' ~ now.w3cDate(),
anselGallery : ':notempty:',
limit : '5'
} %}
I suspect "length" might work instead of notempty, but I don't know how to write that in this format.
Replies
- jmal
Replied 12/18/2017 6:25 PM, Edited 11/10/2018 9:58 AM
Sorry my formatting is jacked up.
- TJ Draper
Replied 12/19/2017 10:45 AM, Edited 11/10/2018 9:58 AM
Unfortunately because Ansel stores images in it's own table, you will not be able to accomplish this with a section query on the element criteria model. I was thinking it might be possible to do this with
craft.ansel.images
, but given your requirements, after looking at it I don't think it actually is possible to do it that way since the only thing I store on the Ansel Images table is the owning element (entry in this case) ID. For what you're trying to do, you might need to do a simple plugin with a custom query that does a join and gets the first image for each entry matching your criteria.Sorry about that. There should definitely be a better way to manage this use case and I’ll give some thought on the best way to build it in.
- jmal
Replied 12/19/2017 12:07 PM, Edited 11/10/2018 9:58 AM
No worries thanks for the reply. It would be a pretty cool feature.
There might be a possible workaround involving looping through each event section and for each entry that doesn't have an image, adding its id to an array that I stick on the end of the actual display loop. For example, the following line works manually, but finding and joining all the excluded IDs from all the sections strikes me as a bit expensive.
... }).id : 'and, not 116, not 86' %} ...
Thoughts? My worry is doing that many round-trips to the db for such a simple piece of the website. It's not the end of the world, I'm mostly curious at this point.