Binding ColdFusion query to DataGrid in Flex


Hi,
In this post I’ll explain you how to bind ColdFusion data into Flex grid.
First, get ready with your cfc.
Your cfc function may look like:

<cffunction name="getCategoryList" access="remote" output="false" returntype="query">
<cfset var qCategoryList = "" />
	<cfquery name="qCategoryList" datasource="#application.dsn#" username="#application.dbuid#" password="#application.dbpwd#">
		SELECT
			categoryId,
			categoryName, 
			Description
		FROM	tblCategory
	</cfquery>
	<cfreturn qCategoryList />
</cffunction>

Please note here that we are returning a ColdFusion query.

Now I’m setting up mxml page to show the grid and fetch the ColdFusion data with RemoteObject.

<?xml version="1.0" encoding="utf-8"?>
<s:Panel xmlns:fx="http://ns.adobe.com/mxml/2009" 
		 xmlns:s="library://ns.adobe.com/flex/spark" 
		 xmlns:mx="library://ns.adobe.com/flex/mx" 
		 creationComplete="categoryGateway.getAllForGrid();">
	<fx:Declarations>
		<s:RemoteObject destination="ColdFusion" source="cfc.categoryGateway" id="categoryGateway">
			<mx:method name="getAllForGrid" result="returnHandler(event)"
					   fault="mx.controls.Alert.show(event.fault.faultString)"/>
		</s:RemoteObject>
	</fx:Declarations>
	<fx:Script>
		<![CDATA[
			import mx.controls.Alert;
			import mx.rpc.events.ResultEvent;
			private function returnHandler(e:ResultEvent):void 
			{
				dgCategory.dataProvider = e.result;
			}
		]]>
	</fx:Script>
	<s:VGroup>
		<mx:DataGrid id="dgCategory">
			<mx:columns>
				<mx:DataGridColumn headerText="Category ID" dataField="categoryId"/>
				<mx:DataGridColumn headerText="Category Name" dataField="categoryName"/>
				<mx:DataGridColumn headerText="Description" dataField="Description"/>
			</mx:columns>
		</mx:DataGrid>
	</s:VGroup>
</s:Panel>

Easy enough?

Now let me point out important notes:

Remember one thing that ActionScript 2.0 and 3.0 are now case sensitive!

So if you write “description” instead of “Description” in DataGridColumn, it wouldn’t bind!

Also If your cfc method returns a ColdFusion structure, then you can get the value of structure elements by typing element name in capital later.

For e.g.

Your cfc method:

<CFSET var myStruct = structNew()>
<CFSET myStruct.query = qGetAllRecord>
<CFSET myStruct.RowCount = qGetAllRecord.recordCount>
<CFRETURN myStruct>

And your ActionScript code would be:

dgCategory.dataProvider = e.result.QUERY;
Alert.show(e.result.ROWCOUNT);
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s