Search code examples
loopscoldfusioncfloop

Sum values in cfloop


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.


Solution

  • 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>