1

I have a (Craft 3) matrix field with two different block types that each have a similar light switch field that I want to use to create anchor links on my page. I need to be able to test whether any of the fields have the light switch enabled, and also loop through all of those entries.

Orignally, both light switch fields were named 'anchor', but that seemed to cause problems, so now they have two different labels. I'm having trouble combining them into a single object though, or even working with them separately in the same template:

{% set anchors = entry.pageBuilder.type('subhead').anchor('= 1') %}
{% set anchorLinks = entry.pageBuilder.type('copy').anchorLink('= 1') %}

Anchors: {{ anchors|length }}
AnchorLinks: {{ anchorLinks|length }}

If I use the code above as-is, the value of one of the objects is always 0. But if I use either of those lines indivdually, they return the proper value.

I also tried merging the two objects, but I still run into the same issue of the value of one of the objects being incorrectly set to 0.

{% set anchors2 = entry.pageBuilder.type('copy').anchorLink('1').find() %}
{% set anchors1 = entry.pageBuilder.type('subhead').anchor('1').find() %}

{% set allAnchors = anchors1|merge(anchors2) %}

one {{ anchors1|length }}
two {{ anchors2|length }}
all {{ allAnchors|length }}

{% for anchor in allAnchors %}
    {{ anchor.subhead }}
{% endfor %}

Is this a bug, or am I doing something wrong?

0

1 Answer 1

2

Keep in mind objects in PHP are always called by reference not by value thus your anchors query will always return blocks from the type subhead with the field value anchor =1 while your matrix query anchorLinks will return blocks of type copy with the field value anchor = 1 and anchorLink = 1

I'm not sure why you don't fetch the results in one single query as it would be faster and easier in my opinion but you want to create 2 queries you need to either reset the previously set property to null or use the clone function

{% set anchors2 = clone(entry.pageBuilder).type('copy').anchorLink('1').all() %}
{% set anchors1 = clone(entry.pageBuilder).type('subhead').anchor('1').all() %}
1
  • Thanks! I somehow missed the changes in Craft 3 that make clone necessary. I would actually prefer to get the results in a single query, but I didn't think it was possible with the two different light switch values. Everything I tried gave me no results.
    – artmem
    Oct 26, 2018 at 14:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.