Use the CFSET tag to define a ColdFusion variable. If the variable already exists, CFSET resets it to the specified value.
<CFSET variable_name=expression>
The following example assigns a new array to the variable "months".
<CFSET months=ArrayNew(1)>
This example creates a variable "Array_Length" that resolves to the length of the array "Scores".
<CFSET Array_Length=ArrayLen(Scores)>
This example assigns to index position two in the array "months" the value "February".
<CFSET months[2]="February">
In this example, the variable name is itself a variable.
<CFSET myvariable="current_value"> <CFSET "#myvariable#"=5>
In this example, a COM object is created. A CFSET defines a value for each method or property in the COM object interface. The last CFSET creates a variable to store the return value from the COM object's "SendMail" method.
<CFOBJECT ACTION="Create" NAME="Mailer" CLASS="SMTPsvg.Mailer"> <CFSET MAILER.FromName=form.fromname> <CFSET MAILER.RemoteHost=RemoteHost> <CFSET MAILER.FromAddress=form.fromemail> <CFSET MAILER.AddRecipient("form.fromname", "form.fromemail")> <CFSET MAILER.Subject="Testing CFOBJECT"> <CFSET MAILER.BodyText="form.msgbody"> <CFSET Mailer.SMTPLog="logfile"> <CFSET success=MAILER.SendMail()> <CFOUTPUT> #success# </CFOUTPUT>
<!--- This example shows how to use CFSET ---> <CFQUERY NAME="GetMessages" DATASOURCE="cfsnippets"> SELECT * FROM Messages </CFQUERY> <HTML> <HEAD> <TITLE> CFSET Example </TITLE> </HEAD> <BODY bgcolor=silver> <H3>CFSET Example</H3> <P>CFSET allows you to set and reassign values to local or global variables within a CF template. <CFSET NumRecords = GetMessages.RecordCount> <P>For example, the variable NumRecords has been declared on this template to hold the amount of records returned from our query (<CFOUTPUT>#NumRecords#</CFOUTPUT>). <P>In addition, CFSET can be used to pass variables from other pages, such as this example which takes the url parameter Test from this link (<a href="cfset.cfm?test=<CFOUTPUT>#URLEncodedFormat(" hey, you, get off of my cloud")#</CFOUTPUT>">click here</A>) to display a message: <P><CFIF IsDefined ("url.test") is "True"> <CFOUTPUT><B><I>#url.test#</I></B></CFOUTPUT> <CFELSE> <H3>The variable url.test has not been passed from another page.</H3> </CFIF> <P>Finally, CFSET can also be used to collect environmental variables, such as the time, the IP address of the user, or any other function or expression possible in ColdFusion. <CFSET the_date = #DateFormat(Now())# & " " & #TimeFormat(Now())#> <CFSET user_ip = CGI.REMOTE_ADDR> <CFSET complex_expr = (23 MOD 12) * 3> <CFSET str_example = Reverse(Left(GetMessages.body, 35))> ...