3

I have a Matrix block with a description field and a number field for hours. Let's say while creating an entry I add in 3 of these blocks with each having a different amount for the hours.

How can I add each of those 3 amounts and get a total amount?

I've spent quite a while researching and can't figure out what kind of syntax would make this work.

4

Twig allows you to add variables just as they were integers. You'll want to setup your totalHours variable before your loop begins so that the totalHours variable is available in the scope outside of the loop itself.

Something like this should work for you:

{# Create a variable to track your total hours #}
{% set totalHours = 0 %}

{% for block in entry.matrixFieldHandle %}

    {% if block.type == 'hoursBlock' %}
        {# Increment your total hours by adding the value
           of your hours block to the current totalHours #}
        {% set totalHours = totalHours + block.hoursFieldHandle %}
    {% endif %}

{% endfor %}

{# Output the result #}
Total Hours: {{ totalHours }}

While I can't test your specific code, here's a generic example that is doing the same thing that will work if you copy and paste it to your template:

{% set totalHours = 0 %}

{% for hours in 0..3 %}
    {% set totalHours = totalHours + hours %}
{% endfor %}

Total Hours: {{ totalHours }}
| improve this answer | |
  • Perfect - It never occurred to me to set the variable initially blank and then iterate over it. Still new to this craft thing :) Thanks! – FortySeven Media Aug 20 '16 at 14:40

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.