Calculated fields should always return a value, whether that is a number from a calculation (as we demonstrate below), some text, a date or any of the other options Coreo allows in this question type.
Example – calculating an area
As a simple example, we will take a form which has two Numeric Answer questions – a length and a width. We can automatically calculate the area by multiplying the length and width together. We will also round the answer to two decimal places.
The Numeric Answer questions will look like:
Both Number Answer questions must be mandatory, as answers are required for your Calculated Field to work.
Adding a calculated fields question
Fill in the question name, answer labels, etc as usual. You are then asked to select a display type.
In this case, we want a ‘Number’ display type, as we will be calculating a number type value from the other Numeric Answer questions. The Display Type must match the ‘type’ returned by the calculation, else no value will be returned. E.g. a Display Type of ‘Text’ when the returned value is a number will not work. The Calculated Field question will look like this:
The calculated fields code editor
Selecting ‘Manage Calculation’ takes you to the code editor as follows:
In this example, we want to calculate the area from the values submitted, so we will add some code to calculate the result of $length * $width, round it to two decimal places, and return it. Text beginning with // double slashes are comments which are helpful to explain your code to other users.
We can add values to $length and $width and use ‘Test Expression’ to check the result before saving. Remember to save your form when you’re finished editing.
When viewing these questions in the Coreo app, you will see the questions as defined, and the Calculated Fields answer will adjust in real-time as you change the answers in the other two questions.
When the record is submitted, you will get all three values in the record – length, width and area.