views:

60

answers:

2

I'm trying to create a recursive function in coldfusion and am coming across some issues.

Here is the logic I have:

<cffunction name="getEvents" access="private">
  <cfargument name="strtdate">
  <cfargument name="parentID" default=0>
  <cfqeury name="qry" datasource="db">
    select *
    from table
    where parentid = #parentid# and 
          starttime between #strtdate# and #DateAdd('d', 1, strtdate)#
  </cfquery>

  <cfset events = arraynew(1)>
  <cfloop query="qry">
    <cfset events[qry.currentrow] = structnew()>
    <cfset events[qry.currentrow].id = qry.id>
    <cfset subevents = getEvents(strtdate, qry.id)>
    <cfif arraylen(subevents)>
      <cfset events[qry.currentrow].subevents = subevents>
    </cfif>
  </cfloop>

  <cfreturn events>
</cffunction>

The problem is that once the function calls itself once it looses the original query in the loop. I now the events are three level deep but I don't want to have to right up the same coded over and over to handle all the events.

I would like to end up with an array of structs that contains all the events and subevents for a given day.

+2  A: 

Make sure you var-scope your variables to keep them local to each invocation of the function.

In your function (at the top if in CF8 or earlier):

<cfset var qry = ''>
<cfset var events = ''>
<cfset var subevents = ''>
Ken Redler
+6  A: 

Try var scoping your query object. In fact you should use proper scoping in general. For example:

<cffunction name="getEvents" access="private">
  <cfargument name="strtdate">
  <cfargument name="parentID" default=0>

  <cfset var qry = "" />
  <cfset var events = "" />
  <!--- etc. --->


  <cfquery name="qry" datasource="db">
    select *
    from table
    where parentid = #parentid# and 
          starttime between #ARGUMENTS.strtdate# 
    and #DateAdd('d', 1, ARGUMENTS.strtdate)#
  </cfquery>

  ... etc.

Otherwise everything is going into the VARIABLES scope and overwriting others I suspect.

Hope that helps!

PS: You should also consider using <cfqueryparam /> in your queries.

Ciaran Archer
And explanation of WHY this is important would help people in the future. Why is this issue caused by not var-scoping the variables?
Edward M Smith
Thanks. That did the trick. I do have CFQueryParam in my code but I didn't want to write more then what I needed to here.
MisterBigs
Edward, I just found this http://www.garyrgilbert.com/tutorials/coldfusion/beginner/scope.cfm
MisterBigs
+1 for `cfqueryparam`
Jordan Reiter