Counting files from structure-field?

I’m having trouble counting and displaying the amount of images in a files-field inside a structure-field.

I’m trying the following:

<?php $blogPosts = $page->blogPosts()->toStructure();
	  foreach($blogPosts->limit(4) as $blogPost): 

      $postImages = $blogPost->images();
	  $imageCount = $postImages->count(); ?>

	  <div id="myElement" data-images="<?= $imageCount ?>">
	     <!-- ... -->
	  </div>

<?php endforeach ?>

But I keep getting this exception error:

I have counted files using count() many times before. Why is it not working here? Does the field behave differently because it is part of a structure-field?

No, it doesn’t behave differently. I assume you field is called images? You have to convert the content of that field to a files object, no matter if that field is inside a structure field or not.

$postImages = $blogPost->images()->toFiles();
$imageCount = $postImages->count(); ?>

The reason why your code works outside of a structure field when the field is called images, is that images() is a page method that gets all images from a page. The field name images in this cases conflicts with the method name.

1 Like