1

I have 3 Matrix fields which define optional parameters for building a query:

  1. A related Entries field
  2. A Categories field
  3. A Tags field

Any combination of them could be used, including none or all.

So I need to build a relTo array to pass into an entries query.

Given that the array might have a length of 1 or greater, it may or may not need an 'and' element.

Does that 'and' have to be first?

I'm assuming it does, so I'm doing something like this:

{# Assume the field handles here exist as **block** fields and **entry** fields #}
{% set cats = block.relCats.all() ?? null %}
{% set rels = block.relEntries.all() ?? null %}
{% set tags = block.relTags.all() ?? null %}

{% set relArr = cats ? [{
    targetElement: cats, 
    field: 'relCats'
}] : [] %}

{% set relArr = rels ? relArr|merge([{
    targetElement: rels, 
    field: 'relEntries'
}]) : relArr %}

{% set relArr = tags ? relArr|merge([{
    targetElement: tags, 
    field: 'relTags'
}]) : relArr %}

So now I have an array which could be empty or have 1, 2 or 3 elements, and which may therefore require an 'and', so I’m assuming I need to do something like this:

{# Build the relTo array #}
{% if relArr|length > 1 %}
    {% set relTo = ['and'] %}

    {% for el in relArr %}
        {% set relTo = relTo|merge([ el ]) %}
    {% endfor %}
{% else %}
    {% set relTo = relArr %}
{% endif %}

{% if relTo|length %}
    {% set entries = craft.entries.section(handle)
        .relatedTo(relTo).limit(6).all() ?? null
    %}
{% else %}
    {% set entries = craft.entries.section(handle)
        .limit(6).all() ?? null
    %}
{% endif %}

Is this right, or is there a more elegant way to build the relTo array?

I'm also now wondering if I need the {% if relTo|length %} conditional or if it's fine to pass an empty array into relatedTo, because it will just get ignored. (I guess I can test that.)

1 Answer 1

1

I've realised (I think) that I can just append 'and' to relArr and then reverse it.

{% set relArr = relArr|length > 1 ? relArr|merge(['and'])|reverse : relArr %}

Gonna try that.

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.