1

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?

2

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 %}
3
  • hmmm... I'm getting error: Twig Runtime Error – Twig\Error\RuntimeError Variable "fields" does not exist. – Lukas Snarskis Mar 11 at 6:33
  • @LukasSnarskis try to copy/paste it from above again, there was just a couple of comments not closed properly. – Oli Mar 11 at 8:34
  • Oops... thanks @Oli – Brad Bell Mar 11 at 23:36

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.