Reputation: 4304
I am referring to a previous SO Coldfusion Calculate Sum Total (Loop? ) that was marked as a correct answer, but the code doesn't work for me.
I am trying to create a grand total from several fields. But the error I receive is that "Variable xxx is not defined". This is because I am trying to append values from the loop for all the records
<cfoutput>
<cfquery name="ActivityReceipts" dbtype="query">
SELECT
activity,
qty_approved,
location,
payment_amount,
shipping_cost,
handling_cost
FROM rc.RC1
WHERE id_number = '#Receipts.id_number#'
</cfquery>
<cfloop query="ActivityReceipts">
<tr>
<td style="text-align:left;">#ActivityReceipts.activity#</td>
<td style="text-align:left;">#ActivityReceipts.qty_approved#</td>
<td style="text-align:left;">#ActivityReceipts.location#</td>
<td style="text-align: right; padding-right: 80px;">#ActivityReceipts.payment_amount#</td>
</tr>
<cfset grandTotal = grandTotal + ( #ActivityReceipts.payment_amount# + #ActivityReceipts.handling_cost# + #ActivityReceipts.Shipping_cost# ) />
</cfloop>
<td>#grandTotal#</td>
</cfoutput>
Note that if I change the grandTotal variable setting line to
<cfset grandTotal = ( #ActivityReceipts.payment_amount# + #ActivityReceipts.handling_cost# + #ActivityReceipts.Shipping_cost# ) />
it does not cause an error, but it also only sums the last row, rather than all of them.
Upvotes: 2
Views: 1279
Reputation: 1490
Start with <cfset grandtotal=0>
before your loop. Since you reference it in your loop, and its not initialized, you're getting undefined.
Upvotes: 2
Reputation: 908
You have to initialize grandTotal
like so:
<cfset grandTotal = 0>
<cfloop query="ActivityReceipts">
<tr>
<td style="text-align:left;">#ActivityReceipts.activity#</td>
<td style="text-align:left;">#ActivityReceipts.qty_approved#</td>
<td style="text-align:left;">#ActivityReceipts.location#</td>
<td style="text-align: right; padding-right: 80px;">
#ActivityReceipts.payment_amount#
</td>
</tr>
<cfset grandTotal = grandTotal + ( ActivityReceipts.payment_amount
+ ActivityReceipts.handling_cost
+ ActivityReceipts.Shipping_cost
) />
</cfloop>
Upvotes: 4
Reputation: 20804
Here's a way to do it without a loop.
grandTotal = ArraySum(ActivityReceipts["payment_amount"])
+ ArraySum(ActivityReceipts["handling_cost"])
+ ArraySum(ActivityReceipts["Shipping_cost"]);
Upvotes: 3
Reputation: 773
you need to set a default for the grandtotal var before the loop...
<cfset grandTotal = 0>
Also, you don't need to put pound signs if you aren't going to output or quote the var.
<cfset grandTotal = grandTotal + ( ActivityReceipts.payment_amount + ActivityReceipts.handling_cost + ActivityReceipts.Shipping_cost ) />
Upvotes: 5
Reputation: 1287
You have to define and initialize the variable grandTotal
before you can do a statement like <cfset grandTotal = grandTotal + ...
. Just do something like:
...
</cfquery>
<cfset grandTotal= 0>
<cfloop query="ActivityReceipts">
...
Upvotes: 2