Getting calculating with forms

Tuesday, December 3, 2024
by Kevin Paxman

Did you know that webforms now have a calculation field that can do math based on user input? In this post, we'll walk through setting up a simple example, but the possibilities are incalculable (see what I did there?).

One thing you might use calculation fields is to give your visitor an estimate of a cost. What we'll build in this example is a simple meal cost estimator.

Select how many of each item you think you will need to feed your party, and we'll give you an estimate of the total.

First, we have a basic HTML element to give an intro to what is expected of a user.

Next, we have a few number fields to provide options to choose from. While number fields are not always the best choice when asking for number input, here it makes sense because this is a field that could reasonably benefit from the "up/down" arrows provided by the number element.

When creating these fields, we try to remember to edit the key to give it a simpler name for later (for example "dessert" is a lot easier to use than "dessert_3_50_").

We configure the number fields to allow a minimum of 0 (you can't order negative quantities of food) and specify that steps should be 1 number apart (no fractional orders for us). We set the title to display after, to make the layout a little cleaner, and we specify that the number fields have a size of 2, both to stop them from displaying at full width and to suggest that we're not expecting huge quantities to be entered.

Before setting up the calculation field, we customize the submit button so it doesn't display - we don't need to do anything with the information people enter, and the calculations update automatically, so there's no need for it.

To get our total cost, we add a calculation field. First, we add the math expression. For this form (assuming you used "ideal" field labels) the math would be:

:main_course|0 * 10 + :side_dish|0 * 5 + :drink|0 * 2 + :dessert|0 * 3.50

We prefix each field's key with a colon (":") and since we didn't make the fields required, we specify that if no value is used, we should treat that as zero was entered. We multiply each field by the cost, and add it all together.

We set the field mask to use currency, so that it starts with a dollar sign and always includes two decimal places. We give the field a size of 6 so it doesn't display at full width.

Save everything and now we have a working form!

Going further

You can combine this with remote fields to pull data from an external dataset, have it populate hidden fields with numbers, and do math on those hidden fields, creating a much more complex - but useful - form.

What other things do you have that could benefit from calculation fields?