Monday, March 28, 2011

ColdMVC: get an object's parents

Awhile back I posted on flattening an array of objects with Parent-Child relationship (link) and have been using it alot. But one issue I had with it was when I was looping through the array of objects I didn't know who my parents were for the current object I was working with. I already knew how deep thanks to the treeDepth property. I made this function to recursively go up the tree of objects and bring back an array of parent objects for an object.


<cffunction name="getObjectsParents" access="public" output="false" returntype="array">
<cfargument name="object" required="true"/>
<cfargument name="result" required="false" default="#[]#"/>

<cfif isObject(arguments.object.parent())>
<cfset arrayPrepend(arguments.result,arguments.object.parent())/>
<cfreturn getObjectsParents(arguments.object.parent(),arguments.result)/>
<cfelse>
<cfreturn arguments.result/>
</cfif>

</cffunction>