1

I am receiving the error message "Impossible to invoke a method ("limit") on an array," but I don't think I am working with an array! Here is why I think that...

First I set an albums variable:

{% set albums = craft.entries.section('townAlbums').with(['townPhotoAlbum']).relatedTo(entry) %}

Then I loop through that object. I'm not calling .all(), so this is still an object, right?

{% for album in albums %}

Finally within this loop I am grabbing one image from the assets field townPhotoAlbum to use as a thumbnail or cover image for this album:

{% set albumCover = album.townPhotoAlbum.limit(1) %}

Why is it complaining about using .limit() on an array when it appears as though I'm still working with an object? Or am I overlooking something woefully obvious?

Thanks!

4

I'm not calling .all(), so this is still an object, right?

Nope. When you execute the for loop, it will explicitly run the database query and return the array of results. You're probably getting a deprecation error logged using that syntax as well since Craft wants you to use {% for album in albums.all() %}

See here in the docs: https://docs.craftcms.com/v3/changes-in-craft-3.html#treating-queries-as-arrays

If you want the first results for the album cover, you can use:

{% set albumCover = album.townPhotoAlbum[0] %}
  • 1
    This answer is almost correct, but I think the actual issue is that the OP is using eager loading (i.e. .with(['townPhotoAlbum'])), which is why album.townPhotoAlbum is an array and not an object (ElementQuery). – Mats Mikkel Rummelhoff Sep 12 '18 at 21:27
  • 1
    @MatsMikkelRummelhoff "almost correct" is what I strive for. Completely overlooked the eager loading part. – Brad Bell Sep 13 '18 at 1:30
  • Oh my gosh, album.townPhotoAlbum[0] is so obvious now. Thanks a bunch, Brad!! – Steven Thate Sep 21 '18 at 14:40

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.