Lists are one of my favorite complex data types
What is a list?
A list is a simple set of data points. A string that can contain multiple values. These values are separated by one or more delimiters. This makes a list a complex data type.
A delimiter is a divider
Overt list: Will, Leroy, Michael, David
Covert list examples:
An Email address: wt@wtomlinson.com ("@" is the delimeter)A Phone number: 402-1234 ("-" is the delimeter)
A Sentence: My name is Will. (A blank space is the delimeter)
Once you recognize these items are lists, you can use CF's powerful set of list functions to perform superhuman tasks!
You've been assigned the task of separating the username from the domain in a customer's email.
Email: wt@wtomlinson.com
<cfscript> //The delimiter in the email below is the @ symbol email = "wt@wtomlinson.com"; // We can use the listFirst() function to extract the username username = listFirst(email, "@"); //The appropriately-named listLast() function takes care of the domain domain = listLast(email, "@"); </cfscript> <cfoutput> Username: #username#<br> Domain: #domain# </cfoutput>
Produces this:
Username: wtDomain: wtomlinson.com
More List Functions (Applied to the same email):
listLen(email, "@") = 2 listAppend(email, "leroy@someplace.com", ",") = wt@wtomlinson.com,leroy@someplace.com
Another trick is using a list as a name for a form input ( I think I learned this little trick from Ray Camden's blog one day). Encode your database values in the list. Then read them when it's submitted. Allows for flexible, powerful, dynamic apps. I can use this technique to display a dynamic amount of rows of product data on the same screen, and allow the user to update each row, in one step, one submit.
<cfoutput query="getProducts"> <tr>blah blah......... <td> <input name="productName_#productID# type="text" /> ........</tr> </cfoutput>
When you submit a form, there's a variable always available called "fieldnames". It is a list. Hey, we can use that!
I only want to run some update queries on the product names only. We've encoded "productName" in the input so we can extract only those fields.
<cfif structKeyExists(form, "submit")>
<!--- Loop over the fieldnames --->
<cfloop list="#form.fieldnames#" index="thisField">
<!--- If its one of our product names, process it --->
<cfif listFirst(thisField, "_") EQ "productName">
<!---Remember, form scope is a structure, so reference the value of the field as a structure
i.e. #form[someVariableAsYourField]#--->
<cfquery.......>
UPDATE tblProducts
SET ProductName = '#form[thisField]#'
WHERE ProductID = #listLast(thisField, "_")#
</cfquery>
</cfif>
</cfloop>
</cfif>
</cfif>