Monday, February 18, 2008

Get All Form Fields in ModelGlue the Elegant Way

If you are using the ModelGlue framework for your ColdFusion development, you know how to get variable values from the form/url scope. Assuming you are inside a controller method that takes the argument "event" of type "ModelGlue.Core.Event", ModelGlue makes this as simple as
where "eventVariableName" is the name of the variable in the form/url scope. Simple enough. However, what happens if you have a form with 10 fields. You could recreate the above with 10 lines with a line for each variable in the form/url scope. Not nice and a bit of a pain. An alternative method would be to great a model cfc containing your getters/setters for each form field. Then using ModelGlue, you would call the "makeEventBean" function passing it the instance of your model and then use model.getName() to get the value of the "name" field.
<cfset formModelCFC = component.createObject("component", "") />
<cfset arguments.event.makeEventBean(formModelCFC) />
<cfset name = formModelCFC.getName() />
If you are interested in traveling that route, the method is described in more detail on Dan Willson's blog under So you want to create a ModelGlue:Unity application? (Part 3)
This method can also be a pain since you have to update your bean every time you add a new field to the form. After a short dicussion with Ray Camden, there is a even easier way using a built in Model-Glue method (that I had initially overlooked). The code is pretty self-explanatory.
<cfset var eventValues = structnew() />

<!--- Get the form/url values --->
<cfset eventValues = arguments.event.getAllValues() />
// //]]>