Using A ColdFusion Structure To Create A Chart
I needed to create a chart showing our meeting registrations. Previously, I was just listing the numbers. However, the CFC function that provided me the data I was using to just list the numbers was a structure where the keys were the meeting codes and the values for the keys were the number of people registered.
At first I thought I would have to build another CFC function to return a query with a count of each meeting's registrations to use the cfchartseries tag's query attribute. But after thinking and experimenting a bit I figured out a way to use the structure I already had as the basis for the chart.
For example of the structure I need to use, see below:
<cfset meetingStruct = structNew() />
<cfset meetingStruct.AN07 = 200 />
<cfset meetingStruct.PI07 = 105 />
<cfset meetingStruct.PD07 = 175 />
<cfset meetingStruct.FM07 = 130 />
Here is the code I used to create a chart using the structure.
<cfchart chartheight="400" chartwidth="600" yaxistitle="Number of Members" title="Meeting Registrations" fontsize="10" show3d="yes" gridlines="5" showmarkers="yes" showxgridlines="yes" >
<cfchartseries type="horizontalbar">
<cfloop list="#ArrayToList(StructSort(meetingStruct, "numeric", "desc"))#" index="key" >
<cfchartdata item="#key#" value="#meetingStruct[key]#" >
</cfloop>
</cfchartseries>
</cfchart>
I placed the cfchartdata tag (which is used to draw the individual bars on the chart) inside a cfloop tag. The cfloop tag is iterating over the keys in the structure.
This part of the cfloop statement: StructSort(meetingStruct, "numeric", "desc") returns an array that is sorted by the values stored in the top level keys of the structure. The array returned contains the structure's keys. For more about StructSort see the description in the CFMX 7 documentation. By using StructSort, my chart data will show the meetings by highest to lowest number of registrations and it is necessary since the output from a Structure is not in any order.
I then covert the array to a list using the ArrayToList function. The cfloop's index variable is named key and will hold the key name each time through the loop. Inside the loop, I use cfchartdata with the item equal to the value of the key variable (which is the meeting code) and the value for that item equals the value stored in that key of the structure (which is the number of people registered for that meeting).
So experimenting, I learned that with a little manipulation you can use a structure as the basis for creating a chart. You can view a test page of here.
Here are some handy references for creating charts in CFMX 7.
It always amazes me how seemingly complex tasks can be accomplished so easily with CF.
How does your CFC get the data(i.e. cfquery from a db)?
D.