You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Drupal Webform中高效求和选中单选框值的Twig实现问题

Drupal Webform 批量求和q_前缀单选框值的解决方法

你当前逐个相加data.q_1 + data.q_2...的方式虽然可行,但字段数量多的时候效率太低。之前用reduce报错Unsupported operand types,主要是三个问题:reduce未指定初始值、单选框值是字符串类型、缺少类型转换。

修正后的Twig代码

在computed_twig元素中使用以下代码即可实现批量求和:

{% set questions = data.qp1.ps1|filter((v, k) => k starts with 'q_') %}
{{ questions|map(v => v|int)|reduce((carry, v) => carry + v, 0) }}

代码说明

  • 过滤字段:通过filter方法筛选出ps1下所有以q_为前缀的字段,k是字段名,v是单选框选中的对应值。
  • 类型转换:用map配合int过滤器,把所有选中的字符串值(比如"1"、"2")转换成整数,避免字符串拼接导致的错误。
  • 安全求和:给reduce指定初始值0,确保第一次计算时carry是数值类型,彻底解决Unsupported operand types错误。

完整的YAML示例(添加总分计算字段)

在你的表单YAML中追加total_score元素即可:

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
# 新增总分计算字段
total_score:
  '#type': computed_twig
  '#title': 'Part I 总分'
  '#template': |
    {% set questions = data.qp1.ps1|filter((v, k) => k starts with 'q_') %}
    {{ questions|map(v => v|int)|reduce((carry, v) => carry + v, 0) }}

内容的提问来源于stack exchange,提问作者Adam888

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 09:57:02