This blog entry discusses how I create a function that queries a database, transforms the query results into XML, and returns the XML in a format that can be used by either Spry (pre-release version 1.3) or Flex 2.0. ColdFusion 7 added a return type of XML (see: ColdFusion 7 documentation). However, I've had to experiment some to get my CFC functions to return XML that can be used by both Spry and Flex 2.0.
My first step is to create a normal CFC function that returns type query and then test the function to ensure I'm getting the data I expect. My next step is to change the return type to xml and transform the query result into an XML format. I use Ray Camden's toXML cfc, which includes several different functions for converting various types (array, structure, list, query) to XML format. The version of toXML that I use can be found here: http://ray.camdenfamily.com/index.cfm/2006/7/13/ToXML-Update
<cffunction name="getPeople" access="remote" returntype="xml" output="false" description="Returns first, last, city, and
presenter id as xml">
<cfset var peopleQry = "">
<cfset var peopleXML = "">
<cfset var parsedPeopleXML = "">
<cfquery name="peopleQry" datasource="#dsn#">
SELECT TOP 50 presenters.presenterID, presenters.firstName as firstName,
presenters.lastName as lastName, presenters.city
WHERE presenters.presenterid > 5000
<!---use Ray Camden's toXML CFC to convert the query to an XML file--->
<cfset toXML = createObject("component", "toXML")>
<!---use the queryToXML function to convert the query results to xml text. dataset will be the name
for the root node and row will be the node that repeats for each row in the query result--->
<cfset peopleXML = toXML.queryToXML(peopleQry, "dataset", "row")>
<!---convert the XML text into an XMLDocument object since we are returning XML--->
<cfset parsedPeopleXML = xmlParse( peopleXML ) >
<!---Set the content returned so that Spry will recognize it as XML. This command is not needed for
Flex 2.0 to use the XML returned, but is needed for Spry. Without this line Spry does not
recognize the returned value as XML.--->
<cfcontent type="application/xml; charset=UTF-8">
<cfreturn parsedPeopleXML />
I then parse into an XML Document the XML string returned by the toXML CFC's queryToXML function. Now what I will return matches the return type I've specified for this function ( xml ).
Lastly, to ensure that Spry recognizes the returned data as XML I use the cfcontent tag to specify the type as XML. Without this step Spry doesn't properly process the returned data. This step is not necessary for Flex 2.0, but since I want to use the same CFC function for both Spry and Flex user interfaces, I include the tag.
You can view a Flex 2.0 demo that uses the XML returned by the above CFC function here: http://www.brucephillips.name/flex/cfxml/bin/cfxml.html and a Spry demo here: http://www.brucephillips.name/flex/cfxml/sprypeople.htm.