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() />


  1. This seems like a problematic approach as you are effectively breaking encapsulation by tying your code to the Form scope (because FieldNames is only created for forms).

    It seems like this would cause problems for unit testing (among other things) where code wouldn't work the same when it is called by a form.

  2. @Steve, technically, you are correct. However, the function and this post clearly indicate that this only is to be used for form fields and not url/session. Any suggestions on making this universal? I know the makeEventBean() method but it's a pain to maintain.

  3. What's wrong with a simple:

    var e = arguments.event;

    var myVar = e.getValue("myVar");

    to shorten things up?

  4. @phil, that would work to shorten things up but still does not resolve having to repeat the code for each form field.


// //]]>