First of all, checking that the field is not empty isn’t the safest way, you need to check the images physical existence before working with it. You should also set the min and max values to 1 in the blueprint so that it is not possible to pick more than one image in that field.
@spanrucker Is there only one image with that template or multiple? In any case, your filter by template will return a collection (even if possible one with one member only) and not a single file object.
And a collection doesn’t have a url() method, you would have to use a foreach loop to go through the collection and then call the url() method on the individual items in the collection.
Late to the party, but glad I found this thread. Have a likewise question but think I understand the matter. Just to be sure I’ll post & hopefully someone can give me heads up on this.
As all files are kept in the same folder for let’s say a project, choosing 1 file of those as cover can be done using a “cover” part in the blueprint and for all files a “gallery” part can be created, right? And am I right that to have only the file targeted as “cover” image it needs a different template?
See this blueprint as example (I removed other types for clarity):
Yes, it can be named anything, it probably makes more sense to call it $cover or $coverImage, to make it clear to your future self what you are trying to fetch here.
The example will not return anything, I guess, because you are nowhere assigning this cover template (at least not in the part of the blueprint you are showing, where the gallery section is missing a template assignment, and the cover section has the template image assigned.
Where are you using first()? findBy() only returns a single element, i.e. the first element that it finds, so no, you don’t need first() in the example and you cannot even used first(), because first() is a collection method, not a single element (collection item) method.
This is short for page.images.filterBy('template', 'cover').first().
FilterBy always returns a collection of images, hence you have to add first() to fetch the first image. Whereas findBy() return a single file object (as mentioned above). The documentation for each method usually tells you exactly what each method returns (there are exceptions where this is less clear, when methods are inherited from parent classes).
When the return type is a class, you can click on it and are redirected to the documentation for that class, with the methods available for this class.