Webform: How to auto-sum numerical fields

To automatically add values together in a Webform, you need at least 3 fields: 2 or more containing the numbers you want to add, and one that does the actual math and contains the total. This tutorial will walk you through the steps of creating an auto-sum set of fields.

Consider an example where you want the user to rate 3 categories so that the total equals 100.

Part 1: The numbers you want to add

Create a "Number" field for each category you want to add. For each one, you probably want to set additional settings, such as the following

  1. Key: Since you'll have to be referring to this field in code later, it is advisable to manually set the "key" to something descriptive and easy to type. Don't forget this step, because the key can't be changed after the field is saved!
  2. Maximum: Since the numbers have to add up to 100, each should have a "maximum" of 100 and probably a "minimum" of 1.
  3. To get whole numbers only (not decimals), you should set the "steps" to 1.
  4. Setting a "Size" of "2" will keep the field from taking up too much space.
  5. "Advanced" tab: Setting a "Default Value" of "0" is optional, but it does help to remind your user that they should be entering a number here.

Repeat these steps for every category you want to add.

Part 2: The Sum field

This is the field that does the work of adding the numbers. Because it is going to use math, it has to rely on the Twig engine that works behind the scenes in Drupal. Under the "Computed" section of the Fields creation screen, choose "Computed Twig."

The magic of this field happens in the section, "Computed value/markup." It starts out looking small, but you can put lots of code in it and it will expand to fit.

  1. Twig uses the characters {{ and }} to indicate that you're giving it data to process, so surround this field with those.
  2. Then use the keys for the form fields that you created in step 1 (in the format "data.form_field_key"), and follow them with + signs to tell Twig to add them.
    The code will look something like this:

    {{ 
    data.first_field +
    data.second_field + 
    data.third_field
    }}
  3. Settings:
    1. Mode: Plain text. This will help if you need to validate this field or use it for conditions on other fields
    2. Remove whitespace around the Computed Value and HTML tags. This also helps with validation and conditions
    3. Automatically update the computed value using Ajax? Usually you'll want to check this box; it's what enables the form to add the numbers as the user enters them. Otherwise, it will only be summed after the form is submitted.