Tuesday, April 26, 2011

ColdFusion's Infline IF (IIF) function

If I have a CFM page that has several CFIF/CFELSE statements, most of the time I'll replace them using ColdFusion's Infline IF (IIF) Function. This decreases the amount of code I have to scroll through within the CFM page.

Take the following CFIF/CFELSE example:

<cfquery name="qName" datasource="dbName">
INSERT INTO tableName (
firstName
lastName
member)
VALUES ('#form.firstName#',
'#form.lastName#',
<cfif isDefined("URL.value")>
member = ''#URL.value#"
<cfelse>
member = 'Non-Member'
</cfif> )
</cfquery>


This can be cleaned up by using ColdFusion's IIF function. Note the IIF function requires the DE function to prevent ColdFusion from evaluating literal strings:

<cfquery name="qName" datasource="dbName">
INSERT INTO tableName (
firstName
lastName
member)
VALUES ('#form.firstName#',
'#form.lastName#',
'#IIF(isDefined("URL.value"), DE("#URL.value#"), DE("Non-Member"))#' )
</cfquery>


I've also used the IIF function to alter the row colors of an HTML table:

<table border="1">
<cfoutput query="qName">
<tr bgcolor="#IIF(qName.currentRow mod 2 eq 0, DE("white"), DE("gray"))#">
<td>
#qName.firstName# #qName.lastName#
</td>
</tr>
</cfoutput>
</table>

No comments: