I want to sum up all values of selected radios (all q_
keys checked values) in a Drupal Webform form. Now I am doing it like this {% set answersTotal = (data.q_1 + data.q_2 + data.q_3 + data.q_4 + data.q_5 )|number_format %} {{ answersTotal }}
and it's working fine but I want a more efficient/simpler way to avoid having to type all the data.q_#
as there are many q_
in each group. I tried this (in a computed_twig
element in Webform) with the reduce filter:
{% set questions = elements.qp1.ps1|filter((v,k) => k starts with 'q_') %} {# this is working fine #}
{{ questions | reduce((carry, v) => carry + v) }} {# this is triggering the error #}
The above is giving me an Unsupported operand types
error.
I also tried this:
{{ questions.value | reduce((carry, v) => carry + v) }}
but it's giving me error:
The "reduce" filter only works with arrays or "Traversable", got "NULL" as first argument in "__string_template__33be2e0acc2d52a6558e04668185b54eb92d8ec87a21403496ffb5af73d8c9d1" at line 5.
The relevant line 5 in the twig template mentioned in the above error is:
echo $this->extensions['Drupal\Core\Template\TwigExtension']->escapeFilter($this->env, twig_array_reduce($this->env, $this->sandbox->ensureToStringAllowed(twig_get_attribute($this->env, $this->source, ($context["questions"] ?? null), "value", [], "any", false, false, true, 5), 5, $this->source), function ($__carry__, $__v__) use ($context, $macros) { $context["carry"] = $__carry__; $context["v"] = $__v__; return (($context["carry"] ?? null) + ($context["v"] ?? null)); }), "html", null, true);
I feel stuck and have no idea in what direction I should move and/or what materials for a newbie I should read to know what I am doing in a better and more organized/structured way.
Here is a minimal sample of my yaml code:
qp1:
'#type': wizard_page
'#title': 'Part I'
'#open': true
ps1:
'#type': details
'#title': title...
'#required': true
'#attributes':
class:
- qp1_1
q_1:
'#type': radios
'#title': q1.....
'#options':
- 'option 1 with value 0'
- 'option 2 with value 1'
- 'option 3 with value 2'
- 'option 4 with value 3'
'#required': true
q_2:
'#type': radios
'#title': q2....
'#options':
- 'option 1 with value 0'
- 'option 2 with value 1'
- 'option 3 with value 2'
- 'option 4 with value 3'
'#required': true
q_3:
'#type': radios
'#title': q3.....
'#options':
- 'option 1 with value 0'
- 'option 2 with value 1'
- 'option 3 with value 2'
- 'option 4 with value 3'
'#required': true
q_4:
'#type': radios
'#title': q4.......
'#options':
- 'option 1 with value 0'
- 'option 2 with value 1'
- 'option 3 with value 2'
- 'option 4 with value 3'
'#required': true
q_5:
'#type': radios
'#title': q5........
'#options':
- 'option 1 with value 0'
- 'option 2 with value 1'
- 'option 3 with value 2'
- 'option 4 with value 3'
'#required': true