Maintaining a Sum in a Loop
Sometimes as you For-Each through results you would like to maintain a running sum. This can be achieved through an EASYProcess ForEach loop and “Sum” Evaluate which is set override itself (NewSum=OldSum+[value]).
In this example we have a table which has user input textboxes. The table has three columns. The product code, a column which denotes if order is placed or not, and a user input for the product cost. Our objective here is to return a total sum of all the the products that have been ordered and display it on the page as “Grand Total”. To achieve this we first run a split over the desired columns. In this case the columns “Order Placed” and “Product Cost” are relevant to us.
Now we set up a For-Each loop that will iterate through the results of the Split service. Before the For-Each loop begins, we set a variable “Sum” as 0. This will be our running count which will grow as we continue the loop.
Inside the Split’s for-each loop, we can first check if the “OrderPlaced” flag is true. When it is equal to “True”, we add its value to the running sum with the “Sum” Evaluate service. Finally when the loop is finished, we have our final total in the “Sum” Evaluate service.
In the SetFieldProperties, we set the “Grand Total” text box with the sum variable by referencing the “Sum” evaluate.
Here we can see that we have two evaluate services named “Sum”.
- The outer “Sum” contains an eval named “Total” that has been initialized to 0.
- The inner “Sum” also contains an eval named “Total”. Here the value of total is set to the effect: (Sum/Total + Split/ProductCost)
This way the inner “Sum” will start off with 0 as the seed value and keep updating itself with the calculated total of the incoming ProductCosts also while making sure their OrderPlaced flag is true. In our example Sum/Total will increment as follows:
- Sum/Total = 0 + 12.49 = 12.49
- Sum/Total = 12.49 + 14.99 = 27.48
- Sum/Total = 27.48 + 9.99 = 37.47
IMPORTANT: For a service to work like this, the OverrideExistingOutput property for the service needs to be set to True.
Below are screenshots of how the sum increments while the For-Each loop runs the rows one after the other.