Creating a ColdFusion Shopping Cart

If you’re considering purchasing a commercial Shopping Cart, or integrating an open source Shopping Cart with your existing site, consider one more option. Creating your own shopping cart really only amounts to a few lines of code.

A typical shopping cart will store a list of products that a user wishes to purchase.  This cart must be available between page requests, but we also want it to disappear when they close their browser or leave the site.

The Session scope is perfect for this.  Any variable or object that you place in the session scope is available to a user session until they close their browser, or the session times-out.  Most shared and managed ColdFusion hosting providers default their session time-out to 20 minutes.

First, you need to make sure your ColdFusion application is setup to handle sessions.  This is accomplished with the <cfapplication> tag.  It is recommended that you place this tag in your Application.cfm file at the root of your site:

Application.cfm

<cfsilent>

<cfapplication name="MySite"
clientmanagement="no"
clientstorage="Cookie"
sessionmanagement="Yes"
setclientcookies="Yes"
sessiontimeout="#CreateTimeSpan(0,0,20,0)#">

</cfsilent>

Using the <cfsilent> tag ensures that there will be no white space in your HTML source, it is a good practice.

To add an item to your shopping cart, use the following code as an example:

<cflock scope="session" type="exclusive" timeout="5">

<cfparam name="session.cart" default="#ArrayNew(1)#">

<cfset sItem = StructNew()>

<cfset sItem.product_id = url.product_id>
<cfset sItem.product = url.product_name>
<cfset sItem.price = url.price>
<cfset sItem.quantity = url.quantity>

<cfset ArrayAppend(session.cart, sItem)>

</cflock>

And finally, to display your shopping cart, simply loop over the session structure as follows:

<table class="cart" cellspacing="0" style="margin-top: 2em;">
<thead>
<tr>
  <th>Product</th>
  <th>Unit Price</th>
  <th>Quantity</th>
  <th>Total</th>
</tr>
</thead>
<cflock scope="session" type="readonly" timeout="5">

<cfparam name="session.cart" default="#ArrayNew(1)#">
<cfset cartSize = ArrayLen(session.cart)>
<cfset total = 0>
<cfloop index="i" from="1" to="#cartSize#">
<tr>
  <td>
    #session.cart[i].product#
  </td>
  <td style="text-align: right;">
    #NumberFormat(session.cart[i].price, "$9.99")#
  </td>
  <td style="text-align: center;">#session.cart[i].quantity#</td>
  <td><cfset itemTotal = session.cart[i].quantity * itemPrice>#NumberFormat(itemTotal, "$9.99")#</td>
  <cfset total = total + itemTotal>
</tr>
</cfloop>
</cflock>
<tr>
  <td colspan="2" style="border: 0;"></td>
  <td style="border-left: 1px solid ##aaa; text-align: right;">Total</td>
  <td style="font-weight: bold; border-left: 0;">#NumberFormat(total, "$9.99")#</td>
  <td style="border-left: 0;">&nbsp;</td>
</tr>
</table>