Earlier today I blogged an example of adding a button to a CFGRID control. A few readers asked I complete the example by hooking up the code to a back end CFC. Here is a simple example of how to do that. First off - be sure to read the first entry so you understand where these code blocks fit in the total picture.

Let's begin by looking at the function that currently responds to the grid click:

<script> function testit(x) { alert(x);} </script>

My first task is to hook this up to the back end. ColdFusion makes this incredibly easy. First I'll add my cfajaxproxy tag:

<cfajaxproxy cfc="test" jsclassname="myproxy">

Back in my JavaScript, I can now create an instance of my CFC using myproxy as a class name:

myproxy = new myproxy();

Next I want to run a function when my server CFC is done:

myproxy.setCallbackHandler(handleResult);

Now let me actually call the CFC back in my testit function:

function testit(x) { myproxy.getData(x); }

"getData" is the name of a CFC method. Let's look at it now:

<cffunction name="getData" access="remote" returnType="string" output="false"> <cfargument name="data" type="any" required="true"> <cfreturn "Yo, you sent me #arguments.data#"> </cffunction>

Obviously real code would do a bit more. The last bit is the result handler I told my code to use:

function handleResult(r) { alert("Result: "+r); }

And that's it. I can't rave enough about cfajaxproxy. Let's look at the complete page (I won't bother posting test.cfc, as all it was was the method above):

<cfajaxproxy cfc="test" jsclassname="myproxy">

<cfquery name="entries" datasource="cfartgallery" maxrows="12"> select * from art </cfquery>

<cfset queryAddColumn(entries, "add", arrayNew(1))>

<cfloop query="entries"> <cfset querySetCell(entries, "add", "<input value='Add' type='button' onclick='javascript:testit(#artid#)'>", currentrow)> </cfloop>

<script> myproxy = new myproxy(); myproxy.setCallbackHandler(handleResult);

function testit(x) { myproxy.getData(x); }

function handleResult(r) { alert("Result: "+r); } </script>

<cfform name="test"> <cfgrid autowidth="true" name="entries" format="html" query="entries" width="600"> <cfgridcolumn name="artid" display="false">

<cfgridcolumn name="artname" header="Name"> <cfgridcolumn name="price" header="Price"> <cfgridcolumn name="add" header="Add"> </cfgrid> </cfform>

Any questions?