TransWikia.com

Getting average of number field values

Craft CMS Asked on July 11, 2021

I’m getting close to finishing my first project on Craft CMS but I have one problem.

I’m using number fields to rate items in my entries. It looks like this:

Text

I will have around 6-7 fields and I need to get the average rating of them to display in the front end.

{% set ratingAverage = entry.dizainas + entry.ekranas + entry.veikimas %}

{% set ratingsSum = ratingAverage / 3 %}

<strong>{{ratingsSum|number(decimals=1)}}</strong>

In fact, some of those fields might be left empty as well so it’s needed to skip them.

Can someone help me out with this?

One Answer

Something like this should work:

{# Setup an arry of the field handles you're interested in #}
{% set fields = ['num1', 'num2', 'num3'] %}

{# set some defaults #}
{% set totalAmount = 0 %}
{% set totalFields = 0 %}

{# loop through the field array #}
{% for field in fields %}

    {# grab the field's value from the entry #}
    {% set value = attribute(entry, field) %}

    {# skip over fields that were left blank, but count fields where 0 was entered #}
    {% if value is not empty and value >= 0 %}

        {# add to the running total and running number of fields with values #}
        {% set totalAmount = totalAmount + value %}
        {% set totalFields = totalFields + 1 %}

    {% endif %}
{% endfor %}

{# do some math #}
{% if totalFields > 0 %}
    {{ (totalAmount / totalFields)|number(decimals=1) }}
{% endif %}

Correct answer by Brad Bell on July 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP