The Robertson Team


 

 
 
 
 
 
  Programmers' Tools >  The Free Stuff >  Free ColdFusion Tutorials >  Code Snippets
 

Code Snippets

When cruising around the CF forums and CF-Talk, I often see solutions I'd like to explore more fully, but just don't have the time for. Bookmarking the thread doesn't really cut it. I created this to help myself remember stuff. No reason why I shouldn't make it publicly available.

Nothing fancy here... just an unlinked list of topics followed by the topics themselves.   Some of this stuff is quite old, and some of it may be out of date. (the design certainly predates the current site and needs a workover).  Use at your own peril.

  • Getting Screen Width and Height Values into CF
  • Building Zillions of Static Pages without Choking CF Server
  • Use 1 Form But Multiple Submit Buttons That Do Different Things
  • Restart CF Server from a browser-based HTML page
  • Use CFMAILPARAM to generate properly formed RFC-Compliant messages
  • getting a TD bgcolor to change on mouseover
  • Export data to Excel
  • Dirt-simple example of setting up an associative array
  • Put the current url (with url vars) into a variable
  • Automatically creating hidden form fields from previous form input
  • URLEncoded encrypt and decrypt example
  • How to determine table or CFGRID size based on browser resolution
  • Clever way to force page refresh
  • Page entry effects
  • Retrieve a list of all submitted form fieldnames
  • Reference a specific query row
  • Using a form to pass a hidden variable in a link
  • Encrypting a variable string
Getting Screen Width and Height Values into CF Posted 03/25/2002
<CFPARAM NAME="variables.FirstVisit" DEFAULT="N" TYPE="string">
<!--- put in some sort of test - a referer test or something
suited to your application to determine if this page view 
is the user's first visit to your site. Set variables.FirstVisit 
to "Y" if its the first visit based on your test--->
<CFIF NOT CompareNoCase(variables.FirstVisit,"Y")>
 <CFOUTPUT>
 <SCRIPT LANGUAGE="JavaScript">
 function SubmitData() {
  document.Elvis.sw.value = screen.width;
  document.Elvis.sh.value = screen.height;
  document.Elvis.submit();
 }
 </SCRIPT>
 <HTML><BODY ONLOAD="SubmitData(); return false;">
 <FORM NAME="Elvis" ONSUBMIT="SubmitData(); return false;" ACTION="#CGI.SCRIPT_NAME#">
 </CFOUTPUT>
 <INPUT TYPE="HIDDEN" NAME="sw">
 <INPUT TYPE="HIDDEN" NAME="sh">
 </FORM>
 </BODY></HTML>
 <CFABORT>
</CFIF>
Building Zillions of Static Pages without Choking CF Server Posted 03/08/2002
<!--- 
This is just something rough I worked out based on someone else's 
post on the CF-Talk list.  you'll need to change the RunRate and 
ReRunRate according to what your server can handle.  The values 
below are probably very conservative. 
You will also need to adjust the values in the cfhttp statement to 
reflect your actual urls and file paths. 
--->
<CFSET variables.DataSource="DSNNAMEHERE">
<CFSET variables.RunRate=20>
<CFSET variables.ReRunRate=60>
<CFSET variables.TotalQty=variables.RunRate*variables.ReRunRate>
<CFPARAM 
 name="url.ThisStart" 
 default="1" 
 TYPE="numeric">
<cfquery 
 name="MakePages" 
 DATASOURCE="#variables.DataSource#"> 
 SELECT 
  Product_id 
 FROM Products 
 WHERE 0=0
 ORDER BY Product_id 
</cfquery> 
<CFIF url.ThisStart GT MakePages.RecordCount>
 <html><head><title>FINISHED</title></head>
 <body BGCOLOR="#FFFFFF" ONLOAD=history.go(1)>
 <FONT FACE="Georgia, Times New Roman, Times">
 <H1><FONT COLOR="#008000">All Done</FONT></H1>
 <B><FONT COLOR="#800000">You should close this browser window</FONT>!</B>
 <P><B>Do NOT press your BACK button</B> to leave.
 </FONT>
 </body></html>
<CFELSE>
 <CFOUTPUT QUERY="MakePages">
  <CFSET form.MessageBody=HomeEdit.Description>
 </CFOUTPUT>
 <CFSET variables.NextStart=url.ThisStart+variables.RunRate>
 <CFSET variables.NextDisplay=url.ThisStart+variables.RunRate-1>
 <CFIF variables.NextDisplay GT MailRun.RecordCount>
  <CFSET variables.NextDisplay=MailRun.RecordCount>
 </CFIF>
 <HTML>
 <CFOUTPUT>
 <meta 
  http-equiv="REFRESH" 
  content="#variables.ReRunRate#; URL=#CGI.SCRIPT_NAME#?ThisStart=#variables.NextStart#">
 </cfoutput>
 <HEAD><TITLE>Mass Page-Maker</TITLE></HEAD>
 <body BGCOLOR="#FFFFFF" ONLOAD=history.go(1)>
 <FONT FACE="Georgia, Times New Roman, Times">
 <CFLOOP 
  QUERY="MakePages" 
  STARTROW="#url.ThisStart#" 
  ENDROW="#variables.NextStart#">
  <CFHTTP 
   URL="http://mydomain/generate.cfm?id=#Product_id#&generate=1" 
   METHOD="GET" 
   PATH="#Map_root#\generate\html\" 
   FILE="#Product_id#.html" 
   RESOLVEURL="false" 
   USERAGENT="Page_Creator">
  </cfhttp> 
 </CFLOOP>
 <CFOUTPUT>
 <H1>Making Pages #url.ThisStart# thru #variables.NextDisplay#</H1>
 <B><FONT COLOR="##008000">Total to send:</FONT> #MakePages.RecordCount#</B><P>
 This page will make pages in batches of #variables.RunRate# at 
#variables.ReRunRate#-second intervalsfor a total rate of #variables.TotalQty# pages per hour. <P>You should leave your computer completely untouched and wait for this job to complete. When it finishes, you will be notified. </CFOUTPUT> </FONT> </body></html> </CFIF>
Use 1 Form But Multiple Submit Buttons That Do Different Things Posted 03/08/2002
<html><head><title></title></head><body>
<cfparam name="form.MyValue" default="" TYPE="string">
<CFIF isdefined ("url.Action")>
 <CFSWITCH EXPRESSION="#url.Action#">
  <CFCASE VALUE="1">
   Submit Method Chosen: ''1''
  </CFCASE>
  <CFCASE VALUE="2">
   Submit Method Chosen: ''2''
  </CFCASE>
  <CFCASE VALUE="3">
   Submit Method Chosen: ''3''
  </CFCASE>
  <CFDEFAULTCASE>
   Action var present but invalid value.
  </CFDEFAULTCASE>
 </CFSWITCH>
</CFIF>
<HR>
<form 
 name="MyMultiForm" 
 action="" 
 method="post">
<CFOUTPUT>
<input 
 type="text" 
 name="MyValue" 
 value="#HTMLEditFormat(form.MyValue)#">
<input 
 type="submit" 
 name="submit1" 
 value="Action 1" 
 onclick="this.form.action='#CGI.SCRIPT_NAME#?Action=1';">
<input 
 type="submit" 
 name="submit2" 
 value="Action 2" 
 onclick="this.form.action='#CGI.SCRIPT_NAME#?Action=2';">
<input 
 type="submit" 
 name="submit3" 
 value="Action 3" 
 onclick="this.form.action='#CGI.SCRIPT_NAME#?Action=3';">
</CFOUTPUT>
</form>
</body></html>
Restart CF Server from a browser-based HTML page Posted 03/08/2002
<!---this has been tested on CF 4.5.1 SP2, may work on earlier or later versions --->
<html><head><title></title></head><body>
<table CellSpacing=2 CellPadding=1 Border=0>
<tr>
<td Width="1">&nbsp;</td>
<td>
<font face="MS Sans Serif, Arial" Size="-2">
The ColdFusion <font size="-1">IDE</font> service must be running 
in order to start and stop ColdFusion services via the browser. 
(The <font size="-1">IDE</font> service can be started from 
the "Services" control panel on Windows NT, or by launching CFIDEService.exe in Windows 95.) 
The ColdFusion Administrator will function only when the ColdFusion service is running.
</font>
<BR><BR>
<table CellSpacing=2 CellPadding=1 Border=0>
<tr>
 <td>
 <font face="MS Sans Serif,Arial" Size="-2"><B>
 ColdFusion Service
 </B></font>&nbsp;&nbsp;
 </td>
 <td VAlign="CENTER">
 <applet 
  codebase="/CFIDE/classes/" 
  code="allaire.cfide.NetscapeApplet" 
  width=124 
  height=22>
 <param 
  name="ApplicationClass" 
  value="allaire.cfide.CFServiceControl">
 <param 
  name="ServiceName" 
  value="Cold Fusion Application Server">
 </applet>
 </td>
</tr>
</table>
</td>
</tr>
</table>
</body></html>
Use CFMAILPARAM to generate more RFC-Compliant messages Posted 03/08/2002
<CFMAIL 
 TO="me@my.com" 
 FROM="you@your.com" 
 SUBJECT="headers test" 
 SERVER="mail.my.com">
 The use of the cfmailparam tag can make CFf-generated 
 messages properly RFC-compliant so they don't get red-flagged 
 by anti-spam systems for being poorly formed.  Use of CF
 variables in the TO and SERVER fields, as well as the CFPARAMS,
 makes global implementation *much* easier.
<CFMAILPARAM NAME="Reply-To" VALUE="me@my.com">
<CFMAILPARAM NAME="Message-ID" VALUE="<#CreateUUID()#@mail.my.com>">
</CFMAIL>
<html><head><title></title></head><body>
Message sent at <CFOUTPUT>#CreateODBCDateTime(Now())#</CFOUTPUT>
</body></html>
getting a TD bgcolor to change on mouseover Posted 06/19/2001
<td 
onmouseover="this.style.backgroundColor='blue';"
onmouseout="this.style.backgroundColor='red';">content</td>
Export data to Excel Posted 02/13/2001
<CFHEADER NAME="Expires" VALUE="#Now()#">
<cfcontent type="application/vnd.ms-excel">
<html>
 <head>
  <title>Untitled</title>
 </head>
 <body>
  <cfquery datasource="investigatorportal" name="getcodedesc">
   select * from code_desc
  </cfquery>
  
  <table>
   <cfoutput query="getcodedesc">
    <tr>
     <td>
      #getcodedesc.code_desc#
     </td>
    </tr>
   </cfoutput>
  </table>
 
 </body>
</html>
Dirt-simple example of setting up an associative array Posted 01/08/2001
<cfset me = StructNew()>
<cfset me.firstName = "hal">
<cfset me.lastName = "helms">
Hello there, #me.firstName#!
Put the current url (with url vars) into a variable Posted 01/07/2001
<cfif Len(Trim(CGI.QUERY_STRING)) GT 0>
  <cfset QueryDelim = "&"
<cfelse>
  <cfset QueryDelim = "">
</cfif>
<cfif CGI.HTTPS EQ "On">
  <cfset HTTPData="https://">
<cfelse>
  <CFSET HTTPData="http://">
</cfif>
<cfset CurrPage=HTTPData & CGI.SERVER_NAME & CGI.PATH_INFO & QueryDelim & CGI.QUERY_STRING>
URLEncoded encrypt and decrypt example Posted 12/18/2000
<PRE><!--- This example shows the use of Encrypt and Decrypt --->
<HTML><HEAD><TITLE>Encrypt Example</TITLE></HEAD><BODY>
<H3>Encrypt Example</H3>
<P>This function allows for the encryption and decryption of a 
string. Try it out by entering your own string and a key of your 
own choosing and seeing the results.
<CFIF isdefined ("url.Action")>
 <CFSET string = FORM.myString>
 <CFSET key = FORM.myKey>
 <CFSET encrypted = encrypt(string, key)>
 <CFSET urlencrypted = URLEncodedFormat(encrypt(string, key))>
 <CFSET decrypted = decrypt(encrypted, key)>
 <!---these next two lines are just here to demo the two steps 
 necessary for decrypting a urlencoded string --->
 <CFSET urldecrypted = URLDecode(urlencrypted)>
 <CFSET urldecrypted = decrypt(urldecrypted, key)>
 <CFOUTPUT>
 <P><B>The string:</B> #string#<P>
 <B>The key:</B> #key#<P>
 <B>Encrypted in normal format:</B> #encrypted#<P>
 <B>Encrypted in URLEncodedFormat:</B> #urlencrypted#<P>
 <B>Decrypted from normal format:</B> #decrypted#<P>
 <B>Decrypted from urlencoded format:</B> #urldecrypted#<P>
 <FORM ACTION="encrypt.cfm?Action=1&ssn=#urlencrypted#" METHOD="post">
 Input your key:<BR>
 <INPUT TYPE="Text" NAME="myKey" VALUE="#form.myKey#">
 <P>Input your string to be encrypted:<BR>
 <textArea NAME="myString" cols="40" rows="5" WRAP="VIRTUAL">#form.myString#</textArea> 
 <P>Here's an html link with the urlencoded string:<BR>
 <textArea 
   NAME="myLink"
   cols="40" 
   rows="5" 
   WRAP="VIRTUAL">&lt;A HREF="http://mydomain/mypage.cfm?ssn=#urlencrypted#"&gt;Click Here&lt;/A&gt;
   </textArea>
 </CFOUTPUT>
<CFELSE>
 <FORM ACTION="encrypt.cfm?Action=1" METHOD="post">
 Input your key:<BR>
 <INPUT TYPE="Text" NAME="myKey">
 <P>Input your string to be encrypted:<BR>
 <textArea NAME="myString" cols="40" rows="5" WRAP="VIRTUAL">123-45-6789</textArea> 
</CFIF>
<INPUT TYPE="Submit" VALUE="Encrypt my String">
</FORM></BODY></HTML></PRE>
How to determine table or CFGRID size based on browser resolution Posted 12/18/2000
<HTML>
<HEAD><TITLE></TITLE>
<CFIF not isdefined ("sw")>
 <SCRIPT LANGUAGE="JavaScript">
 function SubmitData() {
  document.Elvis.sw.value = screen.width;
  document.Elvis.sh.value = screen.height;
  document.Elvis.submit();
 }
 </SCRIPT>
 </HEAD>
 <BODY ONLOAD="SubmitData(); return false;">
 <CFOUTPUT>
 <FORM NAME="Elvis" ONSUBMIT="SubmitData(); return false;" ACTION="#CGI.SCRIPT_NAME#">
 </CFOUTPUT>
 <INPUT TYPE="HIDDEN" NAME="sw">
 <INPUT TYPE="HIDDEN" NAME="sh">
 </FORM>
 </BODY></HTML>
 <CFABORT>
<CFELSE>
 </HEAD><BODY>
</CFIF>
<CFQUERY NAME="MyQuery" DATASOURCE="MySource">
 <!--- do your grid query here --->
</CFQUERY>
<!--- These next two lines use the parameters passed via the javascript above --->
<CFSET gridwidth=(sw - 50)>
<CFSET gridheight=(sh - 50)>
<CFFORM ACTION="foobar.cfm" method="GET">
<cfgrid name="MyGrid"
        height="#gridheight#"
        width="#gridwidth#"
        query="MyQuery"
        insert="Yes"
        delete="Yes"
        font="Arial"
        fontsize="8"
        rowheaders="No"
        selectcolor="##FFFFFF"
        selectmode="EDIT">
<CFGRIDCOLUMN name="TaxRate" header="Rate" dataalign="RIGHT">
<CFGRIDCOLUMN name="State" header="Abbrev">
<CFGRIDCOLUMN name="StateName" header="Name">
</CFGRID>
<BR><INPUT type="Submit" Value="Process All Changes">
</cfform>
</HTML>
Clever way to force page refresh Posted 12/11/2000
if you add the current datetime to the URL (Links, Form action, etc)
this will make the browser think its a new page each time and get freshly called each time.
<a href="newpage.cfm?#urlencodedformat(now())#>
Page entry effects Posted 11/14/2000
<META http-equiv="Page-Enter" content="revealTrans (Duration=5,Transition=17)">
In the above code, the time it takes to 
transition is five seconds and the transition 
effect is #17. Below is a list of all available 
transition effects.
0 Shrinking Box
1 Growing Box 
2 Shrinking Circle 
3 Growing Circle 
4 Wipes Up 
5 Wipes Down 
6 Wipes Right 
7 Wipes Left 
8 Right-Moving Stripes 
9 Downward-Moving Stripes 
10 Right-Moving Boxes 
11 Downward-Moving Boxes 
12 Dissolve Screen 
13 Horizontal Curtain Closing 
14 Horizontal Curtain Opening 
15 Vertical Curtain Closing 
16 Vertical Curtain Opening 
17 Left-Down Wipe 
18 Left-Up Wipe 
19 Right-Down Wipe 
20 Right-Up Wipe 
21 Horizontal Bars Dissolve Screen 
22 Vertical Bars Dissolve Screen 
23 Random Effect
Netscape will ignore these tags.
Retrieve a list of all submitted form fieldnames Posted 11/07/2000
<CFLOOP LIST = "#FORM.FieldName#" INDEX = "ThisField">
 <CFOUTPUT>
  The value of FORM.#ThisField# is #Evaluate("FORM." & ThisField)#<BR>
 </CFOUTPUT>
</CFLOOP>
Reference a specific query row Posted 11/02/2000
<cfset #NumberOfRows# = #A_Number#>
<cfquery name="myquery" datasource="mydbase">
Select field1, field2 From mytable
</cfquery>
<cfoutput> #myquery.field1[NumberOfRows]# </cfoutput>
Using a form to pass a hidden variable in a link Posted 10/22/2000
<cfoutput query="getAll">
<cfform enablecab="no" name="form#Agent_ID#" method="POST" action="test2.cfm">
<input type="hidden" name="AgentID" value="#Agent_ID#">
<tr bgcolor="add8e6">
<td>#FName#</td>
<td>#LName#</td>
<td><a href="javascript: form#Agent_ID#.submit();"> #Agent_ID#</a></td>
<td>#Address_1#</td>
</tr>
</cfform>
</cfoutput>
Encrypting a variable string Posted 10/22/2000
<!---test.cfm--->
<cfset variable = "THIS IS MY TEXT">
<!--- Where foo is a unique key. This can be anything you like. --->
<cfset encrypted = "#encrypt(variable, "foo")#">
<cfoutput>
<p>Encrypted: #encrypted#</p>
<!--- Make sure you use the SAME key to decrypt --->
<p>Decypted: #decrypt(encrypted, "foo")#
<!--- If used in an anchor tag --->
<p><a href="test.cfm?variable=#urlencodedformat(encrypt(variable, "foo"))#">IF IN A URL</a></p>
</cfoutput>


The Robertson Team, TheKing@mysecretbase.com
1.559.360.1717 


HostMySite.com is a leader in ColdFusion web hosting and managed dedicated servers.