Page Controller 1.5 Documentation: Additional Methods

Page Controller Information

Blog Entries

Check Out AFF

Additional Methods

Although the "loadData" method is required, it need not be the only method in your page controller. You can have other methods to translate data between your page and your model or for display logic. Note, however, that your controller should never have any business logic - that is the domain of the model.

For example, you might have a method that returns a query, but you want to have a row of it converted to a structure on the page.

<cfcomponent extends="PageController" output="no">

<cfset loadExternalVars("Contacts",".ContactOMatic")>

<cffunction name="loadData" access="public" returntype="struct" output="no">
	
	<cfset var vars = StructNew()>
	
	<cfset require("URL.id","integer","/")>
	
	<cfset vars.Title = "Hello World">
	<cfset vars.sContact = getContactStruct(URL.id)>
	
	<cfreturn vars>
</cffunction>

<cffunction name="getContactStruct" access="public" returntype="struct" output="no">
	<cfargument name="ContactID" type="numeric" required="true">
	
	<cfset var qContact = variables.Contacts.getContact(arguments.ContactID)>
	
	<cfreturn queryRowToStruct(qContact,1)>
</cffunction>

<cfscript>
/**
* Makes a row of a query into a structure.
*
* @param query      The query to work with.
* @param row      Row number to check. Defaults to row 1.
* @return Returns a structure.
* @author Nathan Dintenfass (nathan@changemedia.com)
* @version 1, December 11, 2001
*/
function queryRowToStruct(query){
    //by default, do this to the first row of the query
    var row = 1;
    //a var for looping
    var ii = 1;
    //the cols to loop over
    var cols = listToArray(query.columnList);
    //the struct to return
    var stReturn = structnew();
    //if there is a second argument, use that for the row number
    if(arrayLen(arguments) GT 1)
        row = arguments[2];
    //loop over the cols and build the struct from the query row    
    for(ii = 1; ii lte arraylen(cols); ii = ii + 1){
        stReturn[cols[ii]] = query[cols[ii]][row];
    }        
    //return the struct
    return stReturn;
}
</cfscript>

</cfcomponent>

You could also call methods of your page controller from that page using Controller.methodname(). For example, to call the "queryRowToStruct" from the page, you could use the following code:

<cfset sMyStruct = Controller.queryRowToStruct(qMyQuery)>