5

I am trying to eager load an image asset assigned to a matrix. The template is pulling entries in from a section and each entry has the matrix field assigned to it that serves as an image gallery.

The error I am getting back using the syntax below is Craft\EntryModel and its behaviors do not have a method or closure named "primaryImage".

Section Handle: products

Matrix Field Handle: gallery

Block Type Handle: productImages

Field Handle: primaryImage, Field Type: Assets

 {% set products = craft.entries({
     section: 'products',
         with:[
                    ['gallery.productImages:primaryImage', {
                      withTransforms: [
                      'heroImage'
                    ]
              }],
          ] 
  }) %}

Template Code:

 {% for entry in products %}
      {% for block in entry.gallery %}
            {% if block.type == 'productImages' %}
                 {% set img = entry.primaryImage[0] ?? null %}
                       {% if img %}
                            <img src="{{ img.url('heroImage') }}">
                       {% endif %}
            {% endif %}
      {% endfor %}
 {% endfor %}
  • Is the primaryImage asset field definitely in the products section field layout? – Luke Pearce Jun 6 '16 at 12:23
  • Yes it's an assets field that belongs to the productImages block type in the gallery Matrix. – triplethreat23 Jun 6 '16 at 17:51
4

The line {% set img = entry.primaryImage[0] ?? null %} is looking for the primaryImage field on the entry inside your for loop. It is not looking for primaryImage for the current matrix field.

If primaryImage is a field within your matrix blog you will need to change the line to

{% set img = block.primaryImage[0] ?? null %}

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.