2

I have a super table that has 4 columns. I'm trying to create an array based off one column (contentType) and merges to get only the unique values while taking the sum of a different column (points). Here is a screen shot:

enter image description here

Based off that screenshot I would have the following results:

  • Motivation-To-Achieve : 2
  • Emotional-Stability : 2
  • Openness : 4

I'm able to get the unique content types, however, I can't figure out how to take the sum of the points column. This is what I have so far:

{% set results = {} %}

{% for row in entry.surveyData %}
    {% set type = row.contentType %}
    {% set pts = row.points %}
    {% set results = results|merge({ (type) : {'name': type, 'points': pts } }) %}
{% endfor %}
  • So you'd want the final sum to equal 8? – Brad Bell Aug 5 '16 at 19:20
  • No, I have the desired results just below the screenshot. – Siebird Aug 5 '16 at 19:43
3

What you need to do is to add the row.points to any existing points for each type, before merging – otherwise you'll just overwrite the existing type/attribute and its values (in other words, the |merge filter won't automatically merge number values inside an object).

Something like this should work – note the use of the |default filter, to fall back to 0 if the results[type] key doesn't exist:

{% set results = {} %}

{% for row in entry.surveyData %}
    {% set type = row.contentType %}
    {% set pts = row.points + results[type].points|default(0) %}
    {% set results = results|merge({ (type) : {'name': type, 'points': pts } }) %}
{% endfor %}
  • Clever! However, getting a error on the front-end Fatal error: Unsupported operand types in /../craft/app/vendor/twig/twig/lib/Twig/Environment.php(403) : eval()'d code on line 67. Does this have to do with the results[type] being in brackets vs curly braces? – Siebird Aug 5 '16 at 19:54
  • No – I just made a typo in my original answer. It should be results[type].points, not results[type] – sorry about that, see edit above :) – Mats Mikkel Rummelhoff Aug 5 '16 at 19:57
  • Fantastic! It's working. Thanks for the help Mats. – Siebird Aug 5 '16 at 20:01
  • No problem. Great that it worked out :) – Mats Mikkel Rummelhoff Aug 5 '16 at 20:06

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.