CF Quick Tip: Display a CFINPUT Element from a CFC

Let’s say you want to write a helper function in a ColdFusion Component (CFC) library, that will draw a HTML FORM field for you and you need to do so using a CFINPUT tag. The ColdFusion compiler will complain if the CFINPUT tag is not inside a CFFORM tag inside that function. This can be a problem if you wish to make this a portable function to be used in any number of form’s.

There is an easy way to get around this. Wrap the CFINPUT element in a CFFORM with an undefined action. Then use a HTML comment tag around the and tags.


<cffunction name="drawDateField" output="true" returntype="void">
   <cfargument name="fieldName" default="" required="true" />
   <cfargument name="dateTime" default="#now()#" />

<!-- <cfform name="foo" action=""> -->
   <cfinput type="text" name="#arguments.fieldName" value="#arguments.dateTime#" onBlur="doSomeFancyValidation()" />
<!-- </cfform> -->


So now, we can use our object on any form in our site that has access to our CFC. It would be a simple call such as:

<cfset objDateLib = createObject("component", "lib.cfc.dateTimeObjects") />

<cfform name="TVScheduler" id="TVScheduler" action="#">
   Start Date = #objDateLib.drawDateField('StartDate', now())#

Be sure to use HTML comment tags and not CFML comment tags. The CFML engine needs to see the CFFORM or it will throw an error. The HTML comment tags will keep your browser from thinking that there are nested FORMs.

Related Posts