1

I don't even know how I should ask the question. I'll try to explain it as clear as I can.

I want to order entries by year-month and output single value (from certain number fields) from all entries from a month like so:

  1. ( July(10) )
  2. ( August(20) )
  3. ( September(30) )

Here is the piece of code I'm trying to figure out:

[
{% set allEntries = craft.entries.section('orders').limit(null).order('postDate desc') %}

{% set currentMonthEarning = 0 %}

{% for year, entriesInYear in allEntries | group("postDate.year") %}
    {% for month, entries in entriesInYear | group("postDate|date('F')" ) %}
        {% for entry in entries %}

            {# fetch aPrice, bPrice, cPrice, but only if > 0 #}
            {% set aPrice = (entry.aPrice > 0) ? entry.aPrice : 0 %}
            {% set bPrice = (entry.bPrice > 0) ? entry.bPrice : 0 %}
            {% set cPrice = (entry.cPrice > 0) ? entry.cPrice : 0 %}

            {% set currentMonthEarning = currentMonthEarning + aPrice + bPrice + cPrice %}

        {% endfor %}

        {{ currentMonthEarning }}{{ not loop.last ? ', ' }}

    {% endfor %}
{% endfor %}
]

Desire output would be: [10,20,30]

What's going on there actually?: It loops through current year's entries from section mySection, then months and then entries. While it loops through entries, it does summing up of three number fields and sets it into the variable currentMonthEarning outside the entries loop.

Current output: [10,30,70]

It seems that currentMonthEarning is passed over to the next "month" with a value set from previous "month" in the loop. The value for the last month (latest) is correct because of ('postDate desc'). If you understand what I'd like can you find a way to get it done?

1
  • 1
    Not sure I'm fully understanding, but are you looking to just reset currentMonthEarning after outputting its value? i.e. {{ currentMonthEarning }}{{ not loop.last ? ', ' }}{% set currentMonthEarning = 0 %}?
    – Brad Bell
    Commented Sep 8, 2016 at 17:15

1 Answer 1

2

You have three for loops, and are setting currentMonthEarning to 0 outside of all of them, and then adding to it (and never resetting it to 0).

Probably you should move the {% set currentMonthEarning = 0 %} inside either the first or second for loop.

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.