7

How do I loop through entries and set a variable if there are any duplicates in the data I'm checking?

In my case, I need to check if there are more than one entry per year. The variable I'm setting will be used in a conditional later in the template.

9

This can be accomplished by creating an array of the entry years. Inside the loop that's building the array, a conditional checks if the year already exists in the array... if the year exists, a variable is set to TRUE which you can use in your conditional later down on the page.

{% set files = craft.entries.section("downloads") %}
{% set dropdown = 0 %}
{% set yearArray = [] %}

{% for entry in files %}
    {% set year = entry.fileDate | date('Y') %}
    {% if year in yearArray %}
        {% set dropdown = 1 %}
    {% endif %}
    {% set yearArray = yearArray | merge([year]) %}
{% endfor %}

{% if dropdown %}
    Do this
{% else %}
    Do this
{% endif %}
4

You could use Craft's group filter:

{% set files = craft.entries.section("downloads") | group('fileDate.year'} %}
{% set dropdown = false %}

{% for year, filesInYear in files %}
    {% if filesInYear|length > 1 %}
        {% set dropdown = true %}
    {% endif %}
{% endfor %}

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.