Alphabetical List of ColdFusion Functions


In the following list, note that you must insert all examples between <cfoutput> and </cfoutput>. In addition, all examples must be enclosed with pound signs (##).

Abs()

Description: Abs() returns the absolute value of a passed number. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Abs(number) 

Example:: The following example returns 5, the absolute value of -5:

 #Abs(-5)# 

See also Sgn()


Acos()

Description: Acos() returns the arccosine of a passed number. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Acos(number) 

Example: The following example returns 1.53578917702, the arccosine of .035:

 #Acos(.035)# 

See also Asin(), Cos(), Pi(), Sin(), Tan()


AddSOAPRequestHeader

Description: AddSOAPRequestHeader() is used to add a SOAP header to a call to a Web Service, prior to calling the Web Service. It is used by code that consumes (as opposed to code that generates) a Web Service. It takes five parameters, all but the last of which are required.

webService is an objecta Web Service created with the CreateObject() function.

name is a string containing the name of the SOAP header you're requesting.

value string or xml object containing the value of the header.

nameSpace is a string containing the namespace for the header.

mustUnderstand is the only optional parameter. It is a logical value which sets the SOAP must Understand value for this header. Defaults to False.

Syntax:

 AddSOAPRequestHeader(webService, headerName, headerValue, headerNameSpace[, mustUnderstand]) 

Example: This example creates an object for a Web Service. It then adds two SOAP headers and calls the function, someFunction(), that is part of the Web Service:

 <cfscript> myWS = CreateObject("webservice",  ~CA "http://www.SomeCFSite.com/SomeWebService.cfc?WSDL"); AddSOAPRequestHeader(myWS, "username", "paul",  ~CA "http://someNameSpace/", false); AddSOAPRequestHeader(myWS, "password", "beatles" ~CA "http://someNameSpace/", false); retVal=myWS.someFunction("value1", "value2"); </cfscript> <!--- get SOAP request and response as XML ---> <cfset soapReq=GetSOAPRequest(myWS)> <cfset soapResp=GetSOAPResponse(myWS)> <cfset xmlRespHeader=GetSOAPResponseHeader(myWS, ~CA "http://someNameSpace", "respHead", true)> <!--- display SOAP response header ---> <cfoutput>#HTMLCodeFormat(xmlRespHeader)#</cfoutput><br /> <!--- display SOAP request ---> <cfoutput>#HTMLCodeFormat(soapReq)#</cfoutput><br /> <!--- display SOAP response ---> <cfoutput>#HTMLCodeFormat(soapResp)#</cfoutput><br /> <!--- Display response Header xml ---> <!--- Display return value ---> <cfdump var="#retVal#"> 

See also AddSOAPResponseHeader(), GetSOAPRequestHeader(), GetSOAPResponseHeader(), GetSOAPRequest(), GetSOAPResponse(), IsSOAPRequest()


AddSOAPResponseHeader

Description: AddSOAPResponseHeader() is used to include a SOAP response header in the Web Service's response. This function is used inside your ColdFusion-built Web Service. It takes four parameters, the last of which is optional.

name is a string containing the name of the SOAP header you're requesting.

value string or xml object containing the value of the header.

nameSpace is a string containing the namespace for the header.

mustUnderstand is the only optional parameter. It is a logical value which sets the SOAP mustUnderstand value for this header. Defaults to False.

Syntax:

 AddSoapResponseHeader(headerName, headerValue, headerNameSpace[, mustUnserstand]) 

Example: The code in this example presents a function in a ColdFusion component being invoked as a webservice. If it is invoked in a context other than that of a Web Service request, it will throw an error.

 <!--- Declare function inside Web Service component ---> <cffunction name="doSomething" access="remote"   output="false"    returntype="string"    displayname="does something"   hint="This function does something">   <!--- Define argument --->   <cfargument name="someArg" required="true" type="string">   <!--- make up return value --->   <cfset retVal="the return value">   <cfset isSOAPRequest = isSOAP()>   <cfif isSOAPRequest>     <!--- get username form request header, as XML  --->     <cfset xmlUser = getSOAPRequestHeader("http://someNameSpace/",     ~CA "username", "TRUE")>     <!--- Add AUTHORIZED VALUE header --->     <cfset addSOAPResponseHeader("http://www.someDomain.com/someNS",     ~CA "respHead", "AUTHORIZED VALUE", false)>   </cfif> <cfreturn retValue> </cffunction> 

See also AddSOAPRequestHeader(),GetSOAPRequestHeader(), GetSOAPResponseHeader(), GetSOAPRequest(), GetSOAPResponse(), IsSOAPRequest()


ArrayAppend()

Description: ArrayAppend() adds an element to the end of an array. ArrayAppend() takes two parameters: the array to which the element is to be appended and the data to be stored in that element. ArrayAppend() returns trUE if the operation is successful.

Syntax:

 ArrayAppend(Array, Value) 

Example: The following example appends an element containing the word January to an array:

 #ArrayAppend(Month, "January")# 

This next example appends an element to a three-dimensional array, setting the value of element [10][1]:

 #ArrayAppend(Users[10][1], "January")# 

NOTE

You can set the values of explicit array elements using the <cfset> tag.


See also ArrayInsertAt(), ArrayPrepend()


ArrayAvg()

Description: ArrayAvg() returns the average numeric value in an array. ArrayAvg() takes a single parameter: the array to be checked.

Syntax:

 ArrayAvg(Array) 

Example: The following example reports the average cost of items in an array:

 The average cost of each item in the list is #DollarFormat(ArrayAvg(items))# 

NOTE

ArrayAvg() works only with arrays containing numeric data. Do not use this function with arrays that contain text data.


See also ArrayMin(), ArrayMax(), ArraySum()


ArrayClear()

Description: ArrayClear() deletes all data from an array. ArrayClear() takes a single parameter: the array to be deleted. ArrayClear() returns trUE if the operation is successful.

Syntax:

 ArrayClear(Array) 

Example: The following example empties an existing array:

 <cfset result = ArrayClear(Items) 

NOTE

ArrayClear() does not delete the actual array. Rather, it removes all the contents from it. The array itself remains and can be reused.


See also ArrayDeleteAt(), ArrayIsEmpty()


ArrayDeleteAt()

Description: ArrayDeleteAt() deletes an element from an array at a specified position, pulling all remaining elements back one place. ArrayDeleteAt() takes two parameters: the array from which to delete the element and the position of the element to delete. ArrayDeleteAt() returns trUE if the operation is successful.

Syntax:

 ArrayDeleteAt(Array, Position) 

Example: The following example deletes the ninth element from an array:

 #ArrayDeleteAt(Items, 9)# 

See also ArrayClear(), ArrayInsertAt()


ArrayInsertAt()

Description: ArrayInsertAt() inserts an element into an array at a specified position, pushing over one place all existing elements with an index greater than the index of the element inserted. ArrayInsertAt() takes three parameters: the array into which to insert the element, the position at which to insert the element, and the data to be stored in that element. ArrayInsertAt() returns trUE if the operation is successful.

Syntax:

 ArrayInsertAt(Array, Position, Value) 

Example: The following example inserts an element containing the word Alaska into the second position of an existing two-dimensional array; it then sets the abbreviation AK into the matching second dimension:

 <cfset result = #ArrayInsertAt(States[1], 2, "Alaska")#> <cfset States[2][2] = "AK"> 

See also ArrayAppend(), ArrayDeleteAt(), ArrayPrepend()


ArrayIsEmpty()

Description: ArrayIsEmpty() checks whether an array has data. ArrayIsEmpty() takes a single parameter: the array to be checked. ArrayIsEmpty() returns trUE if the array is empty and FALSE if not.

Syntax:

 ArrayIsEmpty(Array) 

Example: The following example reports whether an array is empty:

 <cfoutput>Array empty: #YesNoFormat(ArrayIsEmpty(Users))#</cfoutput> 

See also ArrayClear(), ArrayLen(), IsArray()


ArrayLen()

Description: ArrayLen() returns the length of a specified array. ArrayLen() takes a single parameter: the array to be checked.

Syntax:

 ArrayLen(Array) 

Example: The following example reports the size of an array:

 The items array has #ArrayLen(items)# elements 

See also ArrayIsEmpty(), ArrayResize()


ArrayMax()

Description: ArrayMax() returns the largest numeric value in an array. ArrayMax() takes a single parameter: the array to be checked.

Syntax:

 ArrayMax(Array) 

Example: The following example reports the cost of the most expensive item in an array:

 The most expensive item in the list costs #DollarFormat(ArrayMax(items))# 

NOTE

ArrayMax() works only with arrays containing numeric data. Do not use this function with arrays that contain text data.


See also ArrayAvg(), ArrayMin(), ArraySum()


ArrayMin()

Description: ArrayMin() returns the smallest numeric value in an array. ArrayMin() takes a single parameter: the array to be checked.

Syntax:

 ArrayMin(Array) 

Example: The following example reports the cost of the least expensive item in an array:

 The least expensive item in the list costs #DollarFormat(ArrayMin(items))# 

NOTE

ArrayMin() works only with arrays containing numeric data. Do not use this function with arrays that contain text data.


See also ArrayAvg(), ArrayMax(), ArraySum()


ArrayNew()

Description: ArrayNew() is used to create an array. ArrayNew() takes a single parameter: the number of dimensions needed. Valid dimensions are one through three. ArrayNew() returns the array itself.

Syntax:

 ArrayNew(Dimensions) 

Example: The following example creates a one-dimensional array:

 <cfset Users = ArrayNew(1)> 

NOTE

After an array is created, ColdFusion automatically expands it as necessary. Use the ArrayResize() function to resize an array manually.


See also IsArray(), ListToArray()


ArrayPrepend()

Description: ArrayPrepend() adds an element to the beginning of an array. ArrayPrepend() takes two parameters: the array into which to insert the element and the data to be stored in that element. ArrayPrepend() returns trUE if the operation is successful.

Syntax:

 ArrayPrepend(Array, Value) 

Example: The following example inserts an element containing the word Alabama into the beginning of an array:

 #ArrayPrepend(States, "Alabama")# 

NOTE

You can set the values of explicit array elements using the <cfset> tag.


See also ArrayAppend(), ArrayInsertAt()


ArrayResize()

Description: ArrayResize() changes the size of an array, padding it with empty elements if necessary. ArrayResize() takes two parameters: the array to be resized and the size at which to resize it. ArrayResize() returns TRUE if the operation is successful.

Syntax:

 ArrayResize(Array, Size) 

Example: The following example creates an array and immediately resizes it to hold 100 elements:

 <cfset Users = ArrayNew(1)> <cfset result = ArrayResize(Users, 100)> 

TIP

Dynamically expanding arrays is a slow operation. You can dramatically optimize ColdFusion's array processing by resizing the array to the anticipated size immediately after creating it with ArrayNew().


See also ArrayLen(), ArraySet()


ArraySet()

Description: ArraySet() initializes one or more elements in a one-dimensional array with a specified value. ArraySet() takes four parameters: the array itself, the element starting and ending positions, and the value to use. ArraySet() returns trUE if the operation is successful.

Syntax:

 ArraySet(Array, Start, End, Value) 

Example: The following example sets elements 1100 with the value 0:

 #ArraySet(OrderItems, 1, 100, 0)# 

See also ArrayResize(), ArraySort(), ArraySwap()


ArraySort()

Description: ArraySort() sorts the data in an array. ArraySort() takes three parameters: the array to be sorted, the sort type, and an optional sort order of either ascending or descending. If the sort order is omitted, the default order of ascending is used. ArraySort() supports three sort types, as listed in Table C.24.

Table C.24. ArraySort() Sort Types

TYPE

DESCRIPTION

Numeric

Sorts numerically

Text

Sorts text alphabetically, with uppercase before lowercase

TextNoCase

Sorts text alphabetically; case is ignored


Syntax:

 ArraySort(Array, Type [, Order]) 

Example: The following example sorts an array alphabetically using a noncase-sensitive sort (also known as a dictionary sort):

 #ArraySort(Users, "textnocase")# 

NOTE

ArraySort() sorts the actual passed array, not a copy of it.


See also ArraySet(), ArraySwap()


ArraySum()

Description: ArraySum() returns the sum of all values in an array. ArraySum() takes a single parameter: the array to be checked.

Syntax:

 ArraySum(Array) 

Example: The following example reports the total cost of all items in an array:

 The total cost of all item in the list is #DollarFormat(ArraySum(items))# 

NOTE

ArraySum() works only with arrays containing numeric data. Do not use this function with arrays that contain text data.


See also ArrayAvg(), ArrayMin(), ArrayMax()


ArraySwap

Description: ArraySwap() is used to swap the values in two array elements. ArraySwap() takes three parameters: the array itself and the positions of the two elements to be swapped. ArraySwap() returns trUE if the operation is successful.

Syntax:

 ArraySwap(Array, Position1, Position2) 

Example: The following example swaps elements 10 and 11 in an array:

 #ArraySwap(Users, 10, 11)# 

See also ArraySet(), ArraySort()


ArrayToList()

Description: ArrayToList() converts a one-dimensional ColdFusion array into a list. ArrayToList() takes two parameters: the array to be converted and an optional list delimiter. If no delimiter is specified, the default (comma) delimiter is used. ArrayToList() creates a new list.

Syntax:

 ArrayToList (Array [, Delimiter]) 

Example: The following example converts an array of users into a list:

 <cfset UserList = ArrayToList(UserArray)> 

See also ListToArray()


Asc()

Description: Asc() returns the ASCII value of the leftmost character of a string. The Asc() function will return 0 if the string being evaluated is empty.

Syntax:

 Asc(character) 

Example: The following example returns 72, the ASCII value of the character H:

 Asc("Hello") 

TIP

The Asc() function processes only the left-most character in a string. To return the ASCII characters of an entire string, you must loop through the string and process each character individually.


See also Chr(), Val()


Asin()

Description: Asin() returns the arcsine of a passed number in radians. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Asin(number) 

Example: The following example returns 0.0350071497753, the arcsine of .035:

 #Asin(.035)# 

See also Cos(), Pi(), Sin(), Tan()


Atn()

Description: Atn() returns the arctangent of a passed number. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Atn(number) 

Example: The following example returns 0.0349857188285, the arctangent of .035:

 #Atn(.035)# 

See also Cos(), Pi(), Sin(), Tan()


AuthenticatedContext()

Deprecated.

AuthenticatedUser()

Deprecated.

BinaryDecode

Description: Takes a string and converts it to a binary object and returns the binary object. When you have binary data that has been encoded into string format, use this function to convert it back into binary data. Use the binaryEncoding parameter to indicate the encoding algorithm that was used to encode the original binary data. It is intended primarily for use with data that has been encoded using BinaryEncode(). There are three encoding formats: Hex, UU (used in Unix platforms) and Base64.

Encoding is commonly used to move binary data over text-based protocols like HTTP.

Syntax:

 BinaryDecode(string, binaryEncoding) 

Example: This example takes a string variable that had been encoded with BinaryEncode() with Base64 encoding and decodes it back to a binary object so it can be written to disk.

 <cfset binGif = BinaryDecode( strGif, "Base64")> <cffile action="write"    file="C:\cfusion\wwwroot\cfide\images\required2.gif"  variable="binGif" addNewLine="No"> 

See also BinaryEncode(), CharsetEncode(), CharsetDecode(), IsBinary()


BinaryEncode

Description: Takes a binary variable and encodes it, producing a string. When you have binary data that has been encoded into string format, use this function to convert it back into binary data. Use the binaryEncoding parameter to indicate the encoding algorithm that you want to use. There are three encoding formats: Hex, UU (used in Unix platforms) and Base64.

Encoding is commonly used to move binary data over text-based protocols like HTTP.

Syntax:

 BinaryDecode(string, binaryEncoding) 

Example: This example reads a binary file, takes the resulting binary variable, encodes it to a string using Base64 encoding, then displays it on screen.

 <cffile action="readBinary"    file="C:\cfusion\wwwroot\cfide\images\required.gif"  variable="binGif"> <cfset strGif = BinaryEncode( binGif, "Base64")> 

See also BinaryDecode(), CharsetEncode(), CharsetDecode(), IsBinary()


BitAnd()

Description: BitAnd() returns the result of the logical addition two long integers with a bitwise AND operation. This function takes two 32-bit signed integer values as parameters.

Syntax:

 BitAnd(number1, number2) 

Example: The following example returns 5 from 5 and 255:

 #BitAnd(5, 255)# 

See also BitNot(), BitOr(), BitXor()


BitMaskClear()

Description: BitMaskClear() returns the first number with length bits from the starting number through the clear number. This function takes three numeric values as parameters. The first parameter, number, is a 32-bit signed integer. The second and third parameters, start and clear, must be integers between 0 and 31, inclusive.

Syntax:

 BitMaskClear(number, start, clear) 

Example: The following example returns 6 from 6, 31, and 1:

 #BitMaskClear(6, 31, 1)# 

See also BitMaskRead(), BitMaskSet()


BitMaskRead()

Description: BitMaskRead() returns the value of the length bits beginning with the starting number. This function takes three numeric values as parameters. The first parameter, number, is a 32-bit signed integer. The second and third parameters, start and length, must be integers between 0 and 31, inclusive.

Syntax:

 BitMaskRead(number, start, length) 

Example: The following example returns 2 from 22, 3, and 31:

 #BitMaskRead(22, 3, 31)# 

See also BitMaskClear(), BitMaskSet()


BitMaskSet()

Description: BitMaskSet() returns number with mask occupying the bits of length length beginning at the position indicated by the start parameter. This function takes four numeric parameters. The first two parameters, number and mask, are a 32-bit signed integers. The third and fourth parameters, start and length, must be integers between 0 and 31, inclusive. Start is the position where the mask is to start and length is the length of the mask.

Syntax:

 BitMaskSet(number, mask, start, length) 

Example: The following example returns 118 from 22, 3, 5, and 31:

 #BitMaskSet(22, 3, 5, 31)# 

See also BitMaskClear(), BitMaskRead()


BitNot()

Description: BitNot() returns the bitwise NOT of an integer. This function takes only one numeric value as a parameter which must be a signed 32-bit integer.

Syntax:

 BitNot(number) 

Example: The following example returns -23 from 22:

 #BitNot(22)# 

See also BitAnd(), BitOr(), BitXor()


BitOr()

Description: BitOr() returns the bitwise OR of a long integer. This function takes two signed 32-bit integers as parameters. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 BitMaskSet(number1, number2) 

Example: The following example returns 39 from 35 and 7:

 #BitOr(35, 7)# 

See also BitAnd(), BitNot(), BitXor()


BitSHLN()

Description: BitSHLN() returns number bitwise shifted left without rotation by count bits. This function takes two numeric values as parameters. The number parameter must be a signed 32-bit integer. The count parameter must be an integer between 0 and 31.

Syntax:

 BitSHLN(number, count) 

Example: The following example returns 4480 from 35 and 7:

 #BitSHLN(35, 7)# 

See also BitSHRN()


BitSHRN()

Description: BitSHRN()returns number bitwise shifted right without rotation to by count bits. This function takes two numeric values as parameters. The number parameter must be a signed 32-bit integer. The count parameter must be an integer between 0 and 31.

Syntax:

 BitSHRN(number, count) 

Example: The following example returns 250 from 1000 and 2:

 #BitSHRN(1000, 2)# 

See also BitSHLN()


BitXor()

Description: BitXor()returns the closest integer greater than the passed number. You pass two signed 32-bit integers as parameters.

Syntax:

 BitXor(number1, number2) 

Example: The following example returns 1002 from 1000 and 2:

 #BitXor(1000, 2)# 

See also BitAnd(), BitNot(), BitOr()


Ceiling()

Description: Ceiling()returns the nearest integer greater than the passed number. This function takes one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Ceiling(number) 

Example: The following example returns 254 from 253.42:

 #Ceiling(253.42)# 

See also Fix(), Int(), Round()


CharsetDecode()

Description: CharsetDecode() converts string data to binary encoded data using a character set encoding that you specify. The CharsetDecode() function takes two parameters: the string value to be converted and the character encoding specification name and returns a binary object, encoded with that character set. You can use any character set that is recognized by your Java Runtime. Frequently used character sets include:

utf-8

shift_jis

utf-16

iso-2022-jp

iso-8859-1

euc-jp

windows-1252

euc-kr

us-ascii

euc-cn

 

big5


Syntax:

 CharsetDecode(string, charset) 

Example: The following example produces a form into which you can enter a string of text from a different character set, in this case, the Ukrainian character set, Cp1123. Submit the form and it displays the string, converted to binary using Cp1123 and then converted back to string:

 <cfif isDefined("form.data")>   <cfset binData = CharsetDecode(FORM.data, 'Cp1123')>   <cfset strData = CharsetEncode(binData, 'Cp1123')>   <p><strong>binary object dump:</strong> <cfdump var="#binData#"></p>   <p><strong>Encoded back to string:</strong> <cfoutput>#strData#</cfoutput></p> <cfelse>   <form method="post">   <p>Enter text from the Cp1123 (Ukranian) character set.</p>   <input type="Text" name="data">   <input type="Submit">   <p>It will be converted to binary using Cp1123 when you submit the form.</p>   </form> 

See also BinaryEncode(), BinaryDecode(), CharsetEncode(),IsBinary()


CharsetEncode()

Description: CharsetEncode() converts binary data into string data using the character set encoding method of your choice. The CharsetEncode() function takes two parameters: the binary value to be converted and the character encoding specification name and returns the string of characters encoded with that character set. You can use any character set that is recognized by your Java Runtime. Frequently used character sets include:

utf-8

shift_jis

utf-16

iso-2022-jp

iso-8859-1

euc-jp

windows-1252

euc-kr

us-ascii

euc-cn

 

big5


Syntax:

 CharsetEncode(binary data, encoding character set) Example: See the example for CharsetDecode(). 

See also BinaryEncode(), BinaryDecode(), CharsetDecode(),IsBinary()


Chr()

Description: Chr() converts an ASCII value into a printable character. The Chr() function takes a single parameterthe ASCII value to be converted (valid ASCII values range from 0 to 255)and returns the specified ASCII value as a printable character.

Syntax:

 Chr(number) 

Example: The following example returns the letter H, whose ASCII value is 72:

 #Chr(72)# 

See also Asc(), Val()


Cjustify()

Description: CJustify() centers a string within a field of a specified length. It does this by padding spaces before and after the specified text. CJustify() takes two parameters: the string to process and the desired string length.

Syntax:

 CJustify(string, length) 

Example: The following example justifies the word Hello so that it is centered within a 20-character-wide field:

 #CJustify("Hello", 20)# 

See also Ljustify(), Ltrim(), Rjustify(), Rtrim(), Trim()


Compare()

Description: The Compare() function compares two string values. Compare() performs a case-sensitive comparison. This function returns a negative number if the first string is less than the second string, a positive number if the first string is greater than the second string, and 0 if the strings are the same.

Syntax:

 Compare(String1, String2) 

Example: The following example returns a negative value because the first string is less than the second string:

 #Compare("Ben", "Bill")# 

NOTE

The two comparison functions treat white space as characters to be compared. Therefore, if you compare two strings that are identical except for extra spaces at the end of one of them, the compare will not return 0.


TIP

You can create an alphabetical list of strings easily by sorting all the strings in increasing order with the Compare() function.


See also CompareNoCase(), Find()


CompareNoCase()

Description: The CompareNoCase() function compares two string values. CompareNoCase() performs a noncase-sensitive comparison. This function returns a negative number if the first string is less than the second string, a positive number if the first string is greater than the second string, and 0 if the strings are the same.

Syntax:

 CompareNoCase(String1, String2) 

Example: The following example uses the noncase-sensitive comparison function and returns 0 because, aside from case, the strings are the same:

 #CompareNoCase("Michigan", "MICHIGAN")# 

NOTE

The two comparison functions treat white space as characters to be compared. Therefore, if you compare two strings that are identical except for extra spaces at the end of one of them, the compare will not return 0.


See also Compare(), Find()


Cos()

Description: Cos() returns the cosine of an angle in radians. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Cos(number) 

Example: The following example returns 0.540302305868, the cosine of 1:

 #Cos(1)# 

See also Abs(), Acos(), Sgn()


CreateDate()

Description: The CreateDate() function returns a ColdFusion date/time object that can be used with other date-manipulation or formatting functions. CreateDate() takes three parameters: the date's year, month, and day.

Syntax:

 CreateDate(Year, Month, Day) 

Example: The following example creates a date/time object based on three user-supplied fields:

 #CreateDate(birth_year, birth_month, birth_day)# 

TIP

When specifying the year using the CreateDate function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


NOTE

Because the CreateDate function takes no time values as parameters, the time portion of the created date/time object is set to all 0s.


See also CreateDateTime(), CreateODBCDate(), CreateTime()


CreateDateTime()

Description: The CreateDateTime() function returns a ColdFusion date/time object that can be used with other date- and time-manipulation or formatting functions. CreateDateTime() takes six parameters: the date's year, month, and day, and the time's hour, minute, and second.

Syntax:

 CreateDateTime(Year, Month, Day, Hour, Minute, Second) 

Example: The following example creates a date/time object for midnight on New Year's Day, 2002:

 #CreateDateTime(2002, 1, 1, 0, 0, 0)# 

TIP

When specifying the year using the CreateDateTime() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


See also CreateDate(), CreateODBCDateTime(), CreateTime(), ParseDateTime()


CreateODBCDate()

Description: The CreateODBCDate() function returns an ODBC date/time field that can safely be used in SQL statements. CreateODBCDate() takes a single parameter: a ColdFusion date/time object.

Syntax:

 CreateODBCDate(Date) 

Example: The following example creates an ODBC date/time field for the current day (retrieved with the Now() function):

 #CreateODBCDate(Now())# 

NOTE

CreateODBCDate always creates an ODBC date/time field that has the time values set to 0s, even if the passed date/time object had valid time values.


TIP

When specifying the year using the CreateODBCDate function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


TIP

CreateODBCDate() takes a date/time object as a parameter. If you want to pass individual date values as parameters, use the CreateDate() as the function parameter and pass it the values.


See also CreateDate(), CreateODBCDateTime(), CreateODBCTime()


CreateODBCDateTime()

Description: The CreateODBCDateTime() function returns an ODBC date/time field that can safely be used in SQL statements. CreateODBCDateTime() takes a single parameter: a ColdFusion date/time object.

Syntax:

 CreateODBCDate(Date) 

Example: The following example creates an ODBC date/time field for the current day (retrieved with the Now() function):

 #CreateODBCDateTime(Now())# 

TIP

When specifying the year using the CreateODBCDateTime() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


TIP

CreateODBCDateTime() takes a date/time object as a parameter. If you want to pass individual date and time values as parameters, use the CreateDateTime() as the function parameter and pass it the values.


See also CreateDate(), CreateODBCDate(), CreateODBCTime()


CreateODBCTime()

Description: The CreateODBCTime() function returns an ODBC date/time field that can safely be used in SQL statements. CreateODBCTime() takes a single parameter: a ColdFusion date/time object.

Syntax:

 CreateODBCTime(Date) 

Example: The following example creates an ODBC date/time field for the current day (retrieved with the Now function):

 #CreateODBCTime(Now())# 

NOTE

CreateODBCTime() always creates an ODBC date/time field that has the date values set to 0s, even if the passed date/time object had valid date values.


TIP

CreateODBCTime() takes a date/time object as a parameter. If you want to pass individual time values as parameters, use the CreateTime() as the function parameter and pass it the values.


TIP

Always enclose date/time values in quotes when passing them to the CreateODBCTime() function as strings. Without quotes, the value passed is interpreted as a numeral representation of a date/time object.


See also CreateODBCDate(), CreateODBCDateTime(), CreateTime()


CreateObject()

Description: The CreateObject() function creates either a COM, CORBA, or Java object or a ColdFusion component. Note that the syntax varies with the type of object you're creating.

ColdFusion components are special ColdFusion templates (named with the .cfc file extension) that contain CFML code to define functions (methods) and properties. They can be invoked and use in ColdFusion applications like other objects. They can also be invoked by other applications as Web Services.

These tables contain details on this function's parameters, which vary with the type of object being created: Table C.25, Table C.26, Table C.27, and Table C.28.

Table C.25. CreateObject() Parameters for COM

PARAMETER

DESCRIPTION

Type

Required; "COM".

Class

Required; ProgID of the object to be invoked.

Context

Optional; either InProc, Local, or Remote. Default value defined in registry.

Servername

Optional, but required when Context = "Remote". Provides server name in either DNS or UNC format. The following forms are accepted: \\lanserver, lanserver, http://www.myserver.com, www.myserver.com, 127.0.0.1.


Table C.26. CreateObject() Parameters for CORBA

PARAMETER

DESCRIPTION

Type

Required; "CORBA".

Class

Required; if value of Context is "IOR", then this names the file that contains the sharing version of the Interoperable Object Reference (IOR). If value is "NameService", then this is the naming context of the naming service, delimited with forward slashes (e.g., "Macromedia/Department/object").

Context

Required; either "IOR" (to access CORBA server) or "NameService" to use a naming service to access the server. Only valid for VisiBroker.

Locale

Optional; use is specific to VisiBroker orbs. Provides initialization arguments for init_orb(). Available in C++, Version 3.2. Its value must be of the form: "-ORBagentAddr 199.99.129.33 -ORBagentPort 19000". You must use a leading hyphen for each type/value pair.


Table C.27. CreateObject() Parameters for Java Objects

PARAMETER

DESCRIPTION

Type

Required; "Java"

Class

Required; names a valid Java class


Table C.28. CreateObject() Parameters for ColdFusion Components

PARAMETER

DESCRIPTION

Type

Required; "Component"

ComponentName

Required; names the .cfc file containing the CF component


Syntax for COM:

 CreateObject("COM", class, context, servername) 

Syntax for CORBA:

 CreateObject("CORBA", class, context, locale) 

Syntax for Java objects:

 CreateObject("JAVA", class) 

Syntax for ColdFusion components:

 #CreateObject("component", componentname)# 

NOTE

You can also use the <cfobject> tag to instantiate ColdFusion components. The CreateObject() function is intended for use in CFScript.


Example: The following example creates a ColdFusion component object and invokes one of its methods. This assumes that there is a .cfc file in the same directory (as the example), with the name Film_Component.cfc.

 <cfscript> Film = CreateObject("component", "Film_Component"); Filmcount = Film.CheckFilmOrderCount(1); WriteOutput(Filmcount); </cfscript> 

NOTE

COM objects are not supported on Unix platforms.


NOTE

This function may be disabled in the ColdFusion Administrator.


CreateTime()

Description: The CreateTime() function returns a ColdFusion date/time object that can be used with other time-manipulation or formatting functions. CreateTime() takes three parameters: the hour, minute, and second.

Syntax:

 CreateTime(Hour, Minute, Second) 

Example: The following example creates a date/time object based on three ColdFusion fields:

 #CreateTime(act_hr, act_mn, act_se)# 

NOTE

Because the CreateTime() function takes no date values as parameters, the date portion of the created date/time object is set to all 0s.


See also CreateDate(), CreateDateTime(), CreateODBCTime()


CreateTimeSpan()

Description: CreateTimeSpan() creates a date/time object that can be used to rapidly perform date- and time-based calculations. CreateTimeSpan() takes four parameters: days, hours, minutes, and seconds. Any of these values can be set to 0 if not needed.

Syntax:

 CreateTimeSpan(Days, Hours, Minutes, Seconds) 

Example: The following example creates a date/time object with a time exactly six hours from now:

 <cfset detonation# = Now() + CreateTimeSpan(0, 6, 0, 0)> 

TIP

The CreateTimeSpan() function is designed to speed the process of performing date- and time-based calculations. Creating a date/time object with 30 daysand using standard addition operators to add this to an existing date/time objectis quicker than using the DateAdd() function.


TIP

The CreateTimeSpan() function can be used in conjunction with the CACHEDWITHIN attribute of the <cfquery> tag. You can specify a period of time, using CreateTimeSpan(), in which the results of a query will be cached. This use of the CreateTimeSpan() function is effective only if you have enabled query caching in the ColdFusion Administrator.


See also DateAdd()


DateAdd()

Description: DateAdd() is used to add or subtract values to a date/time objectyou can add a week or subtract a year, for example. DateAdd() takes three parameters. The first is the date specifier (see Table C.3); the second is the number of units to add or subtract; and the third is the date/time object to be processed. DateAdd() returns a modified date/time object.

Syntax:

 DateAdd(Specifier, Units, Date) 

Example: The following example returns tomorrow's date (it adds one day to today's date):

 #DateAdd('D', 1, Now())# 

The next example returns a date exactly 10 weeks earlier than today's date:

 #DateAdd('WW', -10, Now())# 

TIP

To subtract values from a date/time object, use the DateAdd function and pass a negative number of units. For example, -5 subtracts five units of whatever specifier was passed.


TIP

You can add or subtract the modified date/time object that DateAdd() returns from other date/time objects and use this value in the CACHEDWITHIN attribute of the <cfquery> tag.


See also CreateTimeSpan()


DateCompare()

Description: DateCompare() enables you to compare two date values to see whether they are the same or whether one is greater than the other. DateCompare() takes two parameters: the dates to compare, which can be specified as date/time objects or string representations of dates. DateCompare() returns -1 if the first date is less than the second date, 0 if they are the same, and 1 if the first date is greater than the second date.

Syntax:

 DateCompare(Date1, Date2) 

Example: The following example verifies that a user-supplied order ship date is valid (not already passed):

 <cfif DateCompare(ship_date, Now()) IS -1>  We can't ship orders yesterday! </cfif> 

See also DateDiff(), DatePart()


DateConvert()

Description: The DateConvert() function converts local machine time to UTC (Universal Coordinated Time) time or vice versa. The DateConvert() function takes two parameters. The first is the conversion type, and the second is the date/time value to be converted. Valid conversion types for the DateConvert() function are "local2utc" and "utc2local". The date/time value to be converted can be constructed using any ColdFusion date/time string. If a calculation for daylight saving time is required, the function uses the settings for the machine that is executing the code.

Syntax:

 DateConvert(conversion_type, date) 

Example: The following example converts the local machine date/time to UTC:

 <cfset TheTime = CreateDateTime(2006, 4, 26, 12, 41, 32)> #DateConvert("local2utc", TheTime)# 

See also CreateDateTime(), DatePart()


DateDiff()

Description: DateDiff() returns the number of units of a passed specifier by which one date is greater than a second date. Unlike DateCompare(), which returns the greater date, DateDiff() tells you how many days, weeks, or months it is greater by. DateDiff() takes three parameters: The first is the date specifier (refer to Table C.3), and the second and third are the dates to compare.

Syntax:

 DateDiff(Specifier, Date1, Date2) 

Example: The following example returns how many weeks are left in this year, by specifying today's date (using the Now() function) and the first date of next year (using the CreateDate function) as the two dates to compare:

 There are #DateDiff("WW", Now(), CreateDate(Year(Now())+1, 1, 1))#  weeks left in this year! 

NOTE

If the first date passed to DateDiff() is greater than the second date, a negative value is returned. Otherwise, a positive value is returned.


TIP

You can add or subtract the modified date/time object that DateDiff() returns from other date/time objects and use this value in the CACHEDWITHIN attribute of the <cfquery> tag.


See also DateCompare(), DatePart()


DateFormat()

Description: DateFormat() displays the date portion of a date/time object in a readable format. DateFormat() takes two parameters: the first is the date/time object to be displayed, and the second is an optional mask value enabling you to control exactly how the data is formatted. If no mask is specified, the default mask of DD-MMM-YY is used. The complete set of date masks is listed in Table C.29.

Table C.29. DateFormat Mask Characters

MASK

DESCRIPTION

D

Day of month in numeric form with no leading 0 for single-digit days.

DD

Day of month in numeric form with a leading 0 for single-digit days.

DDD

Day of week as a three-letter abbreviation (Sun for Sunday, and so on).

DDDD

Day of week as its full English name.

M

Month in numeric form with no leading 0 for single-digit months.

MM

Month in numeric form with a leading 0 for single-digit months.

MMM

Month as a three-letter abbreviation (Jan for January, and so on).

MMMM

Month as its full English name.

Y

Year as last two digits of year, with no leading 0 for years less than 10.

YY

Year as last two digits of year, with a leading 0 for years less than 10.

YYYY

Year as full four digits.

GG

Representative of a period or an era. This mask is currently ignored by ColdFusion but has been reserved for future use.


Syntax:

 DateFormat(Date [, mask ]) 

Example: The following example displays today's date with the default formatting options:

 Today is: #DateFormat(Now())# 

The next example displays the same date but uses the full names of both the day of week and the month:

 It is #DateFormat(Now(), "DDDD, MMMM DD, YYYY")# 

The final example displays today's date in the European format (day/month/year):

 It is #DateFormat(Now(), "DD/MM/YY")# 

NOTE

Unlike the TimeFormat() function mask specifiers, the DateFormat() function mask specifiers are not case-sensitive.


NOTE

DateFormat() supports U.S.-style dates only. Use the LSDateFormat() function for international date support.


See also LSDateFormat(), TimeFormat()


DatePart()

Description: DatePart() returns the specified part of a passed date. DatePart() takes two parameters: The first is the date specifier (refer to Table C.3), and the second is the date/time object to process.

Syntax:

 DatePart(Specifier, Date) 

Example: The following example returns the day of the week on which a user was born (and converts it to a string date using the DayOfWeekAsString function):

 You were born on a #DayOfWeekAsString(DatePart('W', dob))# 

See also DateCompare(), DateDiff(), Day(), DayOfWeek(), DayOfYear(), Hour(), Minute(), Month(), Quarter(), Second(), Week(), Year()


Day()

Description: Day() returns a date/time object's day of month as a numeric value with possible values of 131. Day() takes a single parameter: the date/time object to be processed.

Syntax:

 Day(Date) 

Example: The following example returns today's day of month:

 Today is day #Day(Now())# of this month 

TIP

When specifying the year using the Day() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


See also DayOfWeek(), DayOfYear(), Hour(), Minute(), Month(), Quarter(), Second(), Week(), Year()


DayOfWeek()

Description: DayOfWeek() returns a date/time object's day of week as a numeric value with possible values of 17. DayOfWeek() takes a single parameter: the date/time object to be processed.

Syntax:

 DayOfWeek(Date) 

TIP

When specifying the year using the DayOfWeek() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


TIP

Always enclose date/time values in quotes when passing them to the DayOfWeek() function as strings. Without quotes, the value passed is interpreted as a numeral representation of a date/time object.


Example: The following example returns today's day of week:

 Today is day #DayOfWeek(Now())# of this week 

See also Day(), DayOfYear(), Hour(), Minute(), Month(), Quarter(), Second(), Week(), Year()


DayOfWeekAsString()

Description: DayOfWeekAsString() returns the English weekday name for a passed day-of-week number. DayOfWeekAsString() takes a single parameter: the day of week to be processed, with a value of 17.

Syntax:

 DayOfWeekAsString(DayNumber) 

Example: The following example returns today's day of week:

 Today is day #DayOfWeekAsString(DayOfWeek(Now()))# of this week 

TIP

When specifying the year using the DayOfWeekAsString() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


See also DayOfWeek(), MonthAsString()


DayOfYear()

Description: DayOfYear() returns a date/time object's day of year as a numeric value, taking into account leap years. DayOfYear() takes a single parameter: the date/time object to be processed.

Syntax:

 DayOfYear(Date) 

Example: The following example returns today's day of year:

 Today is day #DayOfYear(Now())# of year #Year(Now())# 

TIP

When specifying the year using the DayOfYear() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


TIP

Always enclose date/time values in quotes when passing them to the DayOfYear() function as strings. Without quotes, the value passed is interpreted as a numeral representation of a date/time object.


See also Day(), DayOfWeek(), Hour(), Minute(), Month(), Quarter(), Second(), Week(), Year()


DaysInMonth()

Description: DaysInMonth() returns the number of days in a specified month, taking into account leap years. DaysInMonth() takes a single parameter: the date/time object to be evaluated.

Syntax:

 DaysInMonth(Date) 

Example: The following example returns the number of days in the current month:

 This month has #DaysInMonth(Now())# days 

TIP

DaysInMonth() takes a date/time object as a parameter, and there is no equivalent function that takes a year and month as its parameters. Fortunately, this easily can be accomplished by combining the DaysInMonth() and CreateDate() functions. For example, to determine how many days are in February 2002, you can create a statement that looks like this: #DaysInMonth(CreateDate(2002, 2, 1))#.


TIP

When specifying the year using the DaysInMonth() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


TIP

Always enclose date/time values in quotes when passing them to the DaysInMonth() function as strings. Without quotes, the value passed is interpreted as a numeral representation of a date/time object.


See also DaysInYear(), FirstDayOfMonth()


DaysInYear()

Description: DaysInYear() returns the number of days in a specified year, taking into account leap years. DaysInYear() takes a single parameter: the date/time object to be evaluated.

Syntax:

 DaysInYear(Date) 

Example: The following example returns the number of days in the current year:

 This year, #Year(Now())#, has #DaysInYear(Now())# days 

TIP

DaysInYear() takes a date/time object as a parameter, and there is no equivalent function that takes just a year as its parameter. Fortunately, this easily can be accomplished by combining the DaysInYear() and CreateDate functions. For example, you can create a statement that looks like this to determine how many days are in the year 2002: #DaysInYear (CreateDate(2002, 1, 1))#.


TIP

When specifying the year using the DaysInYear() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


TIP

Always enclose date/time values in quotes when passing them to the DaysInYear() function as strings. Without quotes, the value passed is interpreted as a numeral representation of a date/time object.


See also DaysInMonth(), FirstDayOfMonth()


DE()

Description: DE() stands for delay evaluation. This function is designed for use with the IIf() and Evaluate() functions, allowing you to pass strings to these functions without their being evaluated.

Syntax:

 DE(String) 

Example: The following example uses DE() to ensure that the string "A" is evaluated, instead of the variable "A".

 #Evaluate(DE("A"))# 

See also IIf(), Evaluate()


DecimalFormat()

Description: DecimalFormat() is a simplified number formatting function that outputs numbers with two decimal places, commas to separate the thousands, and a minus sign for negative values. DecimalFormat() takes a single parameter: the number to be displayed. The DecimalFormat() function will round numbers to the nearest hundredth.

Syntax:

 DecimalFormat(Number) 

Example: The following example displays a table column in the decimal format:

 Quantity: #DecimalFormat(quantity)# 

TIP

For more precise numeric display, use the NumberFormat() function instead.


See also NumberFormat()


Decrypt()

Description: The Decrypt() function enables you to decode strings based on a user-specified key using a symmetric keybased algorithm. This means that the same key that was used to encrypt the string (using Encrypt() and possibly, GenerateSecretKey()) must be used to decrypt the string.

The Decrypt() function takes four parameters. The first parameter is the string on which to perform encryption or decryption. The second parameter is the key with which to encrypt or decrypt the string. The second two, algorithm and encoding are optional. But note that if you use an encoding type, you must also include an algorithm.

The default value for algorithm is ColdFusion's own format, CFMX_COMPAT. It is the least secure. There are four other options; all are presented in Table C.30.

Table C.30. Encryption/Decryption Algorithms

VALUE

DESCRIPTION

AES

Advanced Encryption Standard

BLOWFISH

Created by Bruce Schneier

CFMX_COMPAT

Used by default and all earlier versions of ColdFusion starting with MX

DES

Data Encryption Standard

DESEDE

"Triple DES"


ColdFusion includes the Sun Java Cryptography Extension (JCE) default provider. This provides the algorithms listed in Table C.30 .You can install and use others.

Syntax:

 Decrypt(encrypted_string, key[, algorithm[, encoding]]) 

Example: The following example encrypts a person's name, using the DES algorithm with the keygenerated by the function GenerateSecretKey(), and subsequently decrypts that same string:

 <cfset key=GenerateSecretKey("DES")> <cfset x=Encrypt("John", key, "DES", "Hex")> <cfset y=Decrypt(x, key, "DES", "Hex")> <p>Encrypted: <cfdump var="#x#"></p> <p>Decrypted: <cfdump var="#y#"></p> 

TIP

Remember that when encrypting a string, the string will be UUEncoded after encryption; therefore, the size of the encrypted string can be as much as three times larger than the original string.


See also Encrypt(), GenerateSecretKey()


DeleteClientVariable()

Description: DeleteClientVariable() deletes the client variables whose names are passed as parameters. Unlike other ColdFusion variables, client variables persist over time and must be deleted with this function. DeleteClientVariable() takes a single parameter: the name of the variable to be deleted. DeleteClientVariable() returns TRUE if the variable was deleted. This function deletes a variable even if it did not previously exist. To ensure that a variable actually exists before using the DeleteClientVariable() function, test for its existence with IsDefined().

Syntax:

 DeleteClientVariable(Variable) 

Example: The following example deletes a variable named login_name and sets a local variable with the function's return value:

 <cfset DeleteSuccessful = #DeleteClientVariable("login_name")#> 

See also GetClientVariablesList()


DirectoryExists()

Description: DirectoryExists() checks for the existence of a specified directory and returns either YES or NO. DirectoryExists() takes a single parameter: the name of the directory for which to check. The directory name can't be a relative path but must be specified as a fully qualified path.

Syntax:

 DirectoryExists(Directory) 

Example: The following example checks for the existence of a directory, creating it if it does not exist:

 <cfif #DirectoryExists("#directory#")# IS "No">  <cffile action="Create" directory="#directory#"> </cfif> 

See also FileExists()


DollarFormat()

Description: DollarFormat() is a simplified U.S. currency formatting function that outputs numbers with a dollar sign at the front, two decimal places, commas to separate the thousands, and a minus sign for negative values. DollarFormat() takes a single parameter: the number to be displayed.

Syntax:

 DollarFormat(Number) 

Example: The following example displays the results of an equation (quantity multiplied by item cost) in the dollar format:

 Total cost: #DollarFormat(quantity*item_cost)# 

TIP

For more precise currency display, use the NumberFormat() function instead.


NOTE

DollarFormat() supports U.S. dollars only. Use the LSCurrencyFormat() function for international currency support.


See also LSCurrencyFormat(), NumberFormat()


Duplicate()

Description: The Duplicate() function returns a deep copy of complex variables (like structures). After a variable is duplicated, the duplicate copy of the variable contains no reference to the original variable. The Duplicate() function takes a single parameter: the name of the variable you want to duplicate.

Syntax:

 Duplicate(variable_name) 

Example: The following example duplicates a structure, copying it into the request scope:

 <cflock scope="application" type="readOnly" timeOut="10">  <cfset REQUEST.settings=Duplicate(APPLICATION.settings)> </cflock> 

CAUTION

You can't duplicate COM, CORBA, or Java objects with the Duplicate() function. An attempt to do this causes ColdFusion to throw an exception error.


See also StructCopy()


Encrypt()

Description: The Encrypt() function enables you to encode strings based on a user-specified key using a symmetric-keybased algorithm. This means that the same key that was used to encrypt the string must be used to decrypt the string.

The Encrypt() function takes four parameters. The first parameter is the string on which to perform encryption or decryption. The second parameter is the key (or text seed, in the case of the CFMX_COMPAT algorithm) with which to encrypt or decrypt the string. The second two, algorithm and encoding are optional. But note that if you use an encoding type, you must also include an algorithm.

Note that you should use GenerateSecretKey() (when using any algorithm other than CFMX_COMPAT) to create the key. The CFMX_COMPAT algorithm uses user-defined text seed, rather than an encrypted key.

The default value for algorithm is ColdFusion's own format, CFMX_COMPAT. It is the least secure. There are four other options; all are presented in Table C.30.

Syntax:

 Encrypt(string, key[, algorithm[, encoding]] Example: See the Example for DeCrypt(). 

TIP

Remember that when encrypting a string, the string will be encoded; therefore, the size of the encrypted string can be as much as three times larger than the original string.


See also Decrypt(), GenerateSecretKey().


Exp()

Description: Exp() returns E to the power of a passed number. The constant e equals the base of the natural logarithm, that is 2.71828182845904. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Exp(number) 

Example: The following example returns 148.413159103, the natural logarithm of 5:

 #Exp(5)# 

See also Log(), Log10()


ExpandPath()

Description: ExpandPath() converts a relative or absolute path into a fully qualified path. ExpandPath() takes a single parameter: the path to be converted.

Syntax:

 ExpandPath(Path) 

Example: The following example returns the full path of the server's default document:

 #ExpandPath("index.cfm")# 

Evaluate()

Description: Evaluate() is used to evaluate string expressions. Evaluate() takes one or more string expressions as parameters and evaluates them from left to right.

Syntax:

 Evaluate(String1, ..) 

Example: The following example evaluates the variable A1 through A10:

 <cfloop index="i" from="1" to="10">  <cfoutput>A#I#: #Evaluate("a#i#")#</cfoutput> </cfloop> 

See also DE(), Iif()


FileExists()

Description: FileExists() checks for the existence of a specified file and returns either Yes or No. FileExists() takes a single parameter: the name of the file for which to check. The filename can't be a relative path but must be specified as a fully qualified path.

Syntax:

 FileExists(File) 

Example: The following example checks for the existence of an image file before using it in an IMG tag:

 <cfif #FileExists("C:\root\images\logo.gif")#>  <img src="/books/2/448/1/html/2//images/logo.gif"> </cfif> 

TIP

Use the ExpandPath() function so you don't have to hard-code the filename passed to the FileExists() function; use ExpandPath() to convert the relative path to an actual filename.


See also DirectoryExists()


Find()

Description: Find() performs a case-sensitive search. The first parameter is the string for which to search, and the second parameter is the target string, or string to be searched. The third, optional parameter can specify the position in the target string from which to start the search. This function returns the starting position of the first occurrence of the search string within the specified target string. If the search string is not found, 0 is returned.

Syntax:

 Find(SearchString, TargetString [, StartPosition]) 

Example: The following example returns 18, the starting position of the word America:

 #Find("America", "United States of America")# 

The next example returns 0 because Find() performs a case-sensitive search:

 #Find("AMERICA", "United States of America")# 

The next example searches for the word of in the string The Flag of the United States of America and specifies that the search should start from position 15. The following example returns 31, the position of the second of. Had the optional starting position parameter been omitted, the return value would have been 10, the position of the first of:

 #Find("of", "The Flag of the United States of America", 15)# 

See also FindNoCase(), FindOneOf(), REFind(), REFindNoCase()


FindNoCase()

Description: FindNoCase() performs a noncase-sensitive search. The first parameter is the string, and the second parameter is the target string, or string to be searched. The third, optional parameter can specify the position in the target string from which to start the search. This function returns the starting position of the first occurrence of the search string within the specified target string. If the search string is not found, 0 is returned.

Syntax:

 FindNoCase(SearchString, TargetString [, StartPosition]) 

Example: The following example performs a noncase-sensitive search with the FindNoCase() function:

 #FindNoCase("AMERICA", "United States of America")# 

See also Find(), FindOneOf(), REFind(), REFindNoCase()


FindOneOf()

Description: FindOneOf() returns the position of the first target string character that matches any of the characters in a specified set. FindOneOf() takes three parameters. The first parameter is a string containing the set of characters for which to search. The second parameter is the target string (the string to be searched). The third parameter is an optional starting position from which to begin the search. These functions return the starting position of the first occurrence of any characters in the search set within the specified target string. If no matching characters are found, 0 is returned.

Syntax:

 FindOneOf(SearchSet, TargetString, [, StartPosition]) 

Example: The following example returns the position of the first vowel with a ColdFusion field called LastName:

 The first vowel in your last name is at position #FindOneOf("aeiou", LastName)# 

TIP

The FindOneOf() function is case-sensitive, and there is no noncase-sensitive equivalent function. To perform a noncase-sensitive FindOneOf() search, you first must convert both the search and target strings to either upper- or lowercase (using the UCase() or LCase() function).


See also Find(), FindNoCase()


FirstDayOfMonth()

Description: FirstDayOfMonth() returns the day of the year on which the specified month starts. FirstDayOfMonth() takes a single parameter: the date/time object to be evaluated.

Syntax:

 FirstDayOfMonth(Date) 

Example: The following example returns the day of the year on which the current month starts:

 #FirstDayOfMonth(Now())# 

TIP

FirstDayOfMonth() takes a date/time object as a parameter, and no equivalent function exists that takes just a month and year as its parameters. Fortunately, this can easily be accomplished by combining the FirstDayOfMonth() and CreateDate() functions. For example, to determine the day of the year on which March 1999 started, you can create a statement that looks like this: #FirstDayOfMonth(CreateDate(1999, 3, 1))#.


TIP

When specifying the year using the FirstDayOfMonth() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


TIP

Always enclose date/time values in quotes when passing them to the FirstDayOfMonth() function as strings. Without quotes, the value passed is interpreted as a numeral representation of a date/time object.


See also DaysInMonth(), DaysInYear()


Fix()

Description: If the passed number is greater than or equal to 0, Fix() returns the closest integer that is smaller than the passed number. If not, it returns the closest integer greater than the passed number. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Fix(number) 

Example: The following example returns 1, the closest integer that is smaller than 1.5:

 #Fix(1.5)# 

See also Ceiling(), Int(), Round()


FormatBaseN()

Description: FormatBaseN() converts a number to a string using the base specified. Valid radix values are 236.

Syntax:

 FormatBaseN(Number, Radix) 

Example: The following example converts a user-supplied number into hexadecimal notation:

 #FormatBaseN(Number, 16)# 

To convert a number to its binary format, you can do the following:

 #FormatBaseN(Number, 2)# 

See also InputBaseN()


GenerateSecretKey()

This function generates a secure key for use with Encrypt(). The key is dependent upon the encryption algorithm being used. You indicate which algorithm to be used in the algorithm parameter. Note that the algorithm values are described in Table C.30. You can use any but CFMX_COMPAT.

Note that you don't use GenerateSecretKey() when using the CFMX_COMPAT algorithm as it actually uses a user-supplied text seed value, not a key.

Syntax:

 GenerateSecretKey(algorithm) 

Example: See the example in Decrypt().

GetBaseTagData()

Description: GetBaseTagData() is used within subtags. It returns an object containing data from a specified ancestor tag. GetBaseTagData() takes two parameters: the name of the tag whose data you want returned, and an optional instance number. If no instance is specified, the default value of 1 is used.

Syntax:

 GetBaseTagData(Tag [, InstanceNumber]) 

Example: The following example retrieves the data in a caller <cfhttp> tag:

 #GetBaseTagData(CFHTTP)# 

NOTE

Not all tags contain data (for example, the <cfif> tag). Passing a tag that contains no data to the GetBaseTagData() function causes an exception to be thrown.


See also GetBaseTagList()


GetBaseTagList()

Description: GetBaseTagList() is used within subtags. It returns a comma-delimited list of base tag names. The returned list is in calling order, with the parent tag listed first.

Syntax:

 GetBaseTagList() 

Example: The following example displays the top-level calling tag:

 <cfoutput>The top level tag is #ListFirst(GetBaseTagList())#</cfoutput> 

See also GetBaseTagData()


GetBaseTemplatePath()

Description: GetBaseTemplatePath() returns the full path of the base template. The GetBaseTemplatePath() function takes no parameters.

Syntax:

 GetBaseTemplatePath() 

Example: The following example displays the base template path information to the user:

 <cfoutput> #GetBaseTemplatePath()#</cfoutput> 

See also GetCurrentTemplatePath(), FileExists()


GetClientVariablesList()

Description: GetClientVariablesList() returns a comma-delimited list of the read/write client variables available to the template. The standard read-only system client variables, listed in Table C.31, are not returned. GetClientVariablesList() takes no parameters.

Table C.31. Read-Only Client Variables

VARIABLE

DESCRIPTION

CFID

Unique ID assigned to this client.

CFToken

Unique security token used to verify the authenticity of a CFID value.

URLToken

Text to append to URLs; contains both CFID and CFToken. (Appended automatically to <cflocation> URLs.)


Syntax:

 GetClientVariablesList() 

Example: The following example retrieves the entire list of read/write client variables:

 #ListLen(GetClientVariablesList())# read-write client variables are currently active 

TIP

The list of variables returned by the GetClientVariablesList() function is comma delimited, which makes it suitable for processing with the ColdFusion list functions.


GetContextRoot()

Description: On J2EE server configurations, GetContextRoot() returns the path from the web root to the J2EE context root of the ColdFusion J2EE application. It is the same as calling getpageContext().getRequest().getContextPath(). If the page is in the default (root) context, an empty string is returned. It takes no parameters.

Syntax:

 GetContextRoot() 

Example: This code returns the path to the documentation directory, relative to the J2EE context root.

 <cfset thisURL = "#getContextRoot()#/CFIDE/cfdocs/"> 

See also GetPageContext()


GetCurrentTemplatePath()

Description: GetCurrentTemplatePath() returns the complete path of the template calling this function. The GetCurrentTemplatePath() function does not take any parameters.

Syntax:

 GetCurrentTemplatePath() 

Example: The following example, placed anywhere inside a CFML template, would output the complete path of the template running this code to the user:

 <cfoutput>#GetCurrentTemplatePath()#</cfoutput> 

See also GetBaseTemplatePath(), FileExists()


GeTDirectoryFromPath()

Description: GeTDirectoryFromPath() exTRacts the drive and directory (with a trailing backslash) from a fully specified path. GetdirectoryFromPath() takes a single parameter: the path to be evaluated.

Syntax:

 GetDirectoryFromPath(Path) 

Example: The following example returns the directory portion of a current template's full file path:

 #GetDirectoryFromPath(ExpandPath("*.*") )# 

See also GetFileFromPath()


GetException()

Description: GetException() retrieves a Java exception from a Java object. GetException() takes a single parameter: the Java object to be used.

Syntax:

 GetException(object) 

Example: The following example catches a Java object's exception within a try/catch block:

 <cfcatch type="Any">  <cfset exception=GetException(myObj)>  .. </cfcatch> 

GetFileFromPath()

Description: GetFileFromPath() extracts the filename from a fully specified path. GetFileFromPath() takes a single parameter: the path to be evaluated.

Syntax:

 GetFileFromPath(Path) 

Example: The following example returns the filename portion of a temporary file:

 #GetFileFromPath(GetTempFile(GetTempDirectory(), "CF"))# 

See also GetDirectoryFromPath()


GetFunctionList()

Description: The GetFunctionList() function returns a list of all functions available in ColdFusion. The GetFunctionList() function takes no parameters.

Syntax:

 GetFunctionList() 

Example: The following returns a list of all functions available in ColdFusion:

 <cfset JohnsFunctions = GetFunctionList()> <cfoutput>#StructCount(JohnsFunctions)# functions<br><br></cfoutput> <cfloop COLLECTION="#JohnsFunctions#" ITEM="key">  <cfoutput>#key#<br></cfoutput> </cfloop> 

GetGatewayHelper()

Description: The GetGatewayHelper() function retrieves a Java "Gateway Helper" object for use with a ColdFusion event gateway. The object provides methods and properties that are specific to the gateway. Before you can use this, the event gateway must implement the Gateway Helper class.

GetGatewayHelper() takes one parameter, gatewayID, which must be set to the value of one of the gateway IDs configured in the ColdFusion Administrator.

Syntax:

 GetGatewayHelper(gatewayID) 

Example: The following creates an object named myGateway and will be used to interact with the gateway identified as "Book Club 5551212" in the ColdFusion Administrator:

 <cfset myGateway = #GetGatewayHelper("Book Club 5551212")#> 

See also SendGatewayMessage()


GetHttpRequestData()

Description: The GetHttpRequestData() function retrieves the HTTP request headers and body and makes them available for use in a CFML template. The GetHttpRequestData() function takes no arguments and returns a structure containing the following variables: headers (which returns all the HTTP request headers), content (which returns, in string or binary format, the form data that was submitted by the client), method (which returns the request method as a string), and protocol (which returns the server-based CGI variable Server_Protocol as a string).

Syntax:

 GetHttpRequestData() 

Example: The following example stores all information retrieved by the GetHttpRequestData() function in a variable:

 <cfset headerInfo = #GetHttpRequestData()#> 

GetHttpTimeString()

Description: The GetHttpTimeString function formats a ColdFusion date/time object according to the HTTP standard outlined in RFC 1123. This function takes a single parameter: the date/time object to be formatted.

Syntax:

 GetHttpTimeString(date_time) 

Example: The following example converts the current system time to a date/time format compatible with RFC 1123:

 #GetHttpTimeString(#CreateODBCDateTime(Now())#)# 

TIP

The date/time value that is returned by the GetHttpString() function always is formatted as GMT (Greenwich mean time) to remain consistent with RFC 1123.


GetLocale()

Description: GetLocale() returns the name of the locale currently in use. The locale returned by the GetLocale() function is determined by the native operating system running ColdFusion Application Server.

Syntax:

 GetLocale() 

Example: The following example saves the current locale to a local variable:

 <cfset current_locale = #GetLocale()#> 

See also SetLocale(), GetLocaleDisplayName()


GetLocaleDisplayName()

Displays the name of a locale such that it is appropriately localized to that locale. If no locale is specified in a parameter, it defaults to the current locale of the server, in that locale's language. Note that you can optionally have the specified locale name returned in the language of a different, specified locale.

Syntax:

 GetLocaleDisplayName([locale[,inlocale]]) 

Example: The following example displays the name of the current locale in the locale, French (Canadian):

 <cfset myLocaleNameInFrenchCanadian=~CA  getLocaleDisplayName(getLocale(), "French (Canadian)")> <cfoutput>#myLocaleNameInFrenchCanadian#</cfoutput> 

See also SetLocale(), GetLocale(),


See also server.coldfusion.supportedlocales from Appendix D


GetMetaData()

Description: The GetMetaData() function returns key/value pairs or structured XML data depending on the type of object it is used with. GetMetaData() is used with objects that support introspection, such as ColdFusion components and user-defined functions. It can also be used with query objects.

The scope this is used in component bodies and function bodies at run-time to read and write variables present during the instantiation of the object.

The metadata derived from ColdFusion components is presented as a structure of structures and arrays. The initial structure returned contains the keys presented in Table C.32. Note that other keys may be present for other types of objects.

Table C.32. Metadata Derived from Components

KEY

DESCRIPTION

Name

Component name

Path

Absolute path to the component

Extends

Ancestor component metadata (Name, path and type)

Functions

Array of metadata (structures) for each component function

Type

Type of object being reported on (e.g., "component")

DisplayName

From the <cfcomponent> tag's displayName attribute

Hint

From the <cfcomponent> tag's hint attribute

Output

From the <cfcomponent> tag's output attribute

Properties

An array of metadata (structures) defined by the <cfcomponent> tag's <cfproperty> child tags

UserMetaData

User-defined attributes of the <cfcomponent> tag


The metadata derived from functions contains at least the keys presented in Table C.33. Note that if the function doesn't employ some of the optional attributes, e.g., roles, hint, they will not be present in the metadata.

Table C.33. Metadata Derived from Functions

KEY

DESCRIPTION

Name

Function name

Parameters

Array of structures (argument metadata)

Access

From the <cffunction> tag's access attribute

DisplayName

From the <cffunction> tag's displayName attribute

Hint

From the <cffunction> tag's hint attribute

Output

From the <cffunction> tag's output attribute

ReturnType

From the <cffunction> tag's returnType attribute

Roles

From the <cffunction> tag's roles attribute

UserMetaData

User-defined attributes of the <cffunction> tag


The metadata derived from query objects produces an array of structures. There is one array element (containing one structures) for each field in the query object. The structures contain the elements described in Table C.34.

Table C.34. Metadata Derived from Query objects

KEY

DESCRIPTION

Name

Field

TypeName

Data type name

IsCaseSensitive

True or False


Syntax with objects:

 GetMetaData(Object) 

Syntax from within ColdFusion components:

 GetMetaData(this) 

Example: The following example returns the startup values from a passed variable:

 <!--- define function from which we'll get metadata ---> <cffunction name="myFunction" displayname="My Function"  returntype="string" hint="This is a hint">   <cfargument name="ArgOne" type="string" required="Yes">   <cfreturn reverse(ArgOne)> </cffunction> <!--- get metadata ---> <cfset md = getMetaData(myFunction)> <!--- display metadata ---> <cfdump var="#md#"> 

See also CreateObject()


GetMetricData()

Deprecated.

GetPageContext()

Description: The GetPageContext() function returns the current ColdFusion representation of the Java PageContext object. This object provides access to Java methods and properties that can be useful when integrating J2EE with ColdFusion. Some of these methods (e.g., include() and forward()) can be used like the corresponding JSP tags. This function takes no prameters.

Syntax:

 GetPageContext() 

Example: The following example returns the startup values from a passed variable:

 <!--- Use pageContext() to determine the language of the current locale. Note that getRequest(), getLocale() and getDisplayLanguage() are Java functions. ---> <cfset thisContext = GetPageContext()> Current locale's language: <cfoutput> #thisContext.getRequest().getLocale().getDisplayLanguage()# </cfoutput>. 

See also GetContextRoot()


GetProfileString()

Description: The GetProfileString() function retrieves the value of an entry in an initialization (*.ini) file.

Syntax:

 GetProfileString(iniPath, section, entry) 

Example: The following example returns the startup values from a passed variable:

 <cfoutput>GetProfileString(#FORM.inipath#, "Startup", "OnStartup")</cfoutput> 

See also SetProfileString()


GetSOAPRequest()

Description: The GetSOAPRequest() returns an XML object containing a SOAP header request. It can be called from within a Web Service function or from a client of the Web Service. It takes one parameteran object representation of the Web Servicewhich is required only if the function is being called from the Web Service client (as opposed to within the Web Service itself).

webservice is an object pointing to a Web Service, created by CreateObject() or <cfobject>.

Syntax:

 GetSOAPRequest([webservice]) 

Example: See example for AddSOAPRequestHeader()

See also AddSOAPRequestHeader(), AddSOAPResponseHeader(), GetSOAPRequestHeader(), GetSOAResponse(), GetSOAPResponseHeader(), IsSOAPRequest()


GetSOAPRequestHeader()

Description: The GetSOAPRequestHeader() function retrieves the specified SOAP request header, from within a Web Service function. If it is called in any context other than inside a Web Service function, it will return an error. It takes three parameters, the last of which is optional.

nameSpace is a string containing the namespace for the header.

name is a string containing the name of the SOAP header you're requesting.

asXML a logical value indicating whether or not you want to retrieve the request header as a ColdFusion XML object. Defaults to False. If not set to true, the request header will be returned as a Java object.

Syntax:

 GetSOPARequestHeader(nameSpace, name[, asXML]) 

Example: See the example in AddSOAPResponseHeader() for an example of the usage of GetSOAPRequestHeader().

See also AddSOAPRequestHeader(), AddSOAPResponseHeader(), GetSOAPRequest(), GetSOAResponse(), GetSOAPResponseHeader(), IsSOAPRequest()


GetSOAPResponse()

Description: The GetSOAPResponseHeader() function retrieves the specified SOAP response, after invoking a Web Service. The SOAP response is retrieved as a ColdFusion XML object. It takes one parameter, an object representing the Web Service. Note that the Web Service must be invoked prior to calling GetSOAPResponse().

webservice is a ColdFusion object representation of the Web Service.

Syntax:

 GetSOAPResponse(webservice) 

Example: See the example in AddSOAPRequestHeader() for usage of GetSOAPResponse().

See also AddSOAPRequestHeader(), AddSOAPResponseHeader(), GetSOAPRequestHeader(), GetSOARequest(), GetSOAPResponseHeader(), IsSOAPRequest()


GetSOAPResponseHeader()

Description: The GetSOAPResponseHeader() function retrieves the specified SOAP response header. This function is called from a Web Service client, after invoking the Web Service. It takes four parameters, the last of which is optional.

webservice is a ColdFusion object returned by CreateObject() or <cfobject>.

nameSpace is a string containing the namespace for the header.

name is a string containing the name of the SOAP header you're requesting.

asXML is the only optional parameter. It is a logical value; when set to true, the header will be returned as a ColdFusion XML object. Defaults to False. If set to False, the header will be returned as a Java object.

Syntax:

 GetSOPARequestHeader(webservice, nameSpace, name[, asXML]) 

Example: See example in AddSOAPRequestHeader() for an example of the usage of GetSOAPRequestHeader().

See also AddSOAPRequestHeader(), AddSOAPResponseHeader(), GetSOAPRequest(), GetSOAResponse(), GetSOAPResponseHeader(), IsSOAPRequest()


GetTempDirectory()

Description: The GetTempDirectory() function retrieves the full pathname of the temp directory on which ColdFusion Server is installed.

Syntax:

 GetTempDirectory() 

Example: The following example returns the temp directory pathname:

 <cfoutput>#GetTempDirectory()#</cfoutput> 

See also GetTempFile()


GetTempFile()

Description: GetTempFile() returns the full path to a temporary file for use by your application. The returned filename is guaranteed to be unique. GetTempFile() takes two parameters: The first is the directory where you want the temporary file created, and the second is a filename prefix of up to three characters. You can't omit the prefix, but you can pass an empty string ("").

Syntax:

 GetTempFile(Directory, Prefix) 

Example: The following example returns the name of a temporary file beginning with the letters CF in the Windows temporary directory:

 #GetTempFile(GetTempDirectory(), "CF")# 

TIP

To create a temporary file in the Windows temporary directory, pass the GetTempDirectory() function as the directory parameter.


See also GetTempDirectory()


GetTemplatePath()

Deprecated.

GetK2ServerCollections()

Deprecated.

GetK2ServerDocCount()

This function has been deprecated.

GetK2ServerDocCountLimit()

This function has been deprecated.

GetTickCount()

Description: GetTickCount() performs timing tests with millisecond accuracy. The value returned by GetTickCount is of no use other than to compare it with the results of another GetTickCount() call to check time spans.

Syntax:

 GetTickCount() 

Example: The following example tests how long a code block takes to execute:

 <cfset count1 = #GetTickCount()#> <cfset count2 = #GetTickCount()#> <cfset duration = count2-count1> <cfoutput>Code took #duration# milliseconds to execute</cfoutput> 

GetTimeZoneInfo()

Description: The GetTimeZoneInfo() function returns a structure containing relevant time zone information from the machine on which the code is run. The GetTimeZoneInfo() function does not take any parameters, and the structure returned contains four elements with the keys outlined in Table C.35.

Table C.35. GetTimeZoneInfoKeys Returned in Structure

KEY

DESCRIPTION

utcTotalOffset

Returns the difference in local time (time captured from the machine executing the code) from UTC (Universal Coordinated Time). A plus sign lets you know that the time zone you are comparing is west of UTC; a minus sign lets you know that the time zone you are comparing is east of UTC.

utcHourOffset

Returns the difference in local time from UTC in hours.

utcMinuteOffset

Returns the difference in local time from UTC in minutes, after the hours offset has been figured in. For some countries, such as those in North America, the minute offset is 0 because these countries' times are offset from UTC by exactly n hours. However, the times of some countries in the world are offset from UTC by n hours and n minutes.

isDSTOn

Returns TRUE if daylight saving time is on in the machine executing the code; otherwise, if daylight saving time is off, it returns FALSE.


Syntax:

 GetTimeZoneInfo() 

Example: The following example uses GetTimeZoneInfo() to compare UTC offsets with the local time:

 <cfset myTime = GetTimeZoneInfo()> <cfoutput> The difference in local time from UTC in seconds is #myTime.utcTotalOffset#.<br> The difference in local time from UTC in hours is #myTime.utcHourOffset#.<br> The difference in local time from UTC in minutes is #mytime.utcMinuteOffset#.<br> </cfoutput> 

See also DateConvert(), CreateDateTime(), DatePart()


GetToken()

Description: Tokens are delimited sets of data within a string. The GetToken() function enables you to extract a particular token from a string by specifying the token number, or index. GetToken() takes three parameters. The first is the string to search. The second is the index of the token to extract; 3 will extract the third token and 5 will extract the fifth, for example. The third parameter is an optional set of delimiters GetToken() uses to determine where each token starts and finishes. If the delimiter's parameter is not provided, the default of spaces, tabs, and new-line characters is used. The default delimiters effectively enable this function to be used to extract specific words for a string. GetToken() returns the token in the specified position or any empty string if Index is greater than the number of tokens present.

Syntax:

 GetToken(String, Index [, Delimiters]) 

Example: The following example uses a hyphen as a delimiter to extract just the area code from a phone number:

 #GetToken("800-555-1212", 1, "-")# 

TIP

Use the ColdFusion list functions instead of GetToken() when working with strings that contain lists of data.


See also Left(), Right(), Mid(), SpanExcluding(), SpanIncluding()


Hash()

Description: The Hash() function converts a string into a 32-byte hexadecimal string using the one-way algorithm. Because this conversion is one way, a string that has been converted to hexadecimal using the Hash() function can't be converted back to its original form.

The Hash() function requires a single parameter: the string to be converted using Hash(). You can optionally specify the algorithm and type of encoding to be used as well. You can't specify the encoding type without also specifying the algorithm. The encoding type must be a name recognized by the Java runtime. The default value is the value is normally UTF-8, and it's specified with the defaultCharset entry in the runtime.xml file. It will be ignored when using the CFMX_COMPAT algorithm. The algorithm defaults to CFMX_COMPAT but you can use any of the algorithms in Table C.36.

Table C.36. Algorithms Available For the Hash() Function

ALGORITHM

DESCRIPTION

MD5

Default algorithm; generates 32-bit hexadecimal string.

CFMX_COMPAT

Generates a hashed string; same type produced by Hash() function in versions of ColdFusion prior to version 7.

SHA

Secure Hash Standard SHA-1; produces a 28-character string.

SHA-256

Secure Hash Standard; produces a 44-character string.

SHA-384

Secure Hash Standard; produces a 64-character string.

SHA-512

Secure Hash Standard; produces an 88-character string.


Syntax:

 Hash(string[, algorithm[, encoding]]) 

Example: The following example hashes a user-defined password value:

 #Hash("#form.password#")# 

TIP

The Hash() function is useful for converting sensitive data (such as user passwords) into a hexadecimal string for storage in the database. If you store the converted value in the database, you can then have users reenter their passwords, hash the value they enter, and compare the hexadecimal string returned with the hexadecimal value stored in the database.


Hour()

Description: Hour() returns a date/time object's hour as a numeric value with possible values of 023. Hour() takes a single parameter: the date/time object to be processed.

Syntax:

 Hour(Date) 

Example: The following example returns the current hour of the day:

 This is hour #Hour(Now())# of the day 

TIP

When specifying the year using the Hour() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


TIP

Always enclose date/time values in quotes when passing them to the Hour() function as strings. Without quotes, the value passed is interpreted as a numeral representation of a date/time object.


See also Day(), DayOfWeek(), DayOfYear(), Minute(), Month(), Quarter(), Second(), Week(), Year()


HTMLCodeFormat()

Description: HTMLCodeFormat() displays text with HTML codes with a preformatted HTML block (using the <pre> and </pre> tags). HTMLCodeFormat() takes a single parameter: the text to be processed. When you evaluate a string with the HTMLCodeFormat() function, all carriage returns are removed from the string and all special characters contained within the string are escaped.

Syntax:

 HTMLCodeFormat(Text) 

Example: The following example uses preformatted text to display the code used to generate a dynamic Web page:

 #HTMLCodeFormat(page)# 

TIP

HTMLCodeFormat() is useful for displaying data in FORM TEXTAREA fields.


See also HTMLEditFormat(), ParagraphFormat()


HTMLEditFormat()

Description: HTMLEditFormat() converts supplied text into a safe format, with any HTML control characters converted to their appropriate entity codes. HTMLEditFormat() takes a single parameter: the text to be converted.

Syntax:

 HTMLEditFormat(Text) 

Example: The following example displays the HTML code used to render a dynamic Web page inside a bordered box:

 <table border>  <tr>  <td>#HTMLEditFormat(page)#</td>  </tr> </table> 

TIP

Use HTMLEditFormat() to display HTML code and tags within your page.


See also HTMLCodeFormat(), ParagraphFormat()


IIf()

Description: IIf() evaluates a Boolean condition and evaluates one of two expressions depending on the results of that evaluation. If the Boolean condition returns TRUE, the first expression is evaluated; if the condition returns FALSE, the second expression is evaluated.

Syntax:

 IIF(Boolean condition, Expression if TRUE, Expression if FALSE) 

Example: The following example determines whether #cnt# has a value of 1; it evaluates "A" if it does and "B" if it does not:

 #IIf("#cnt# IS 1", "A", "B")# 

See also DE(), Evaluate()


IncrementValue()

Description: The IncrementValue() function increments the passed number by 1. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 IncrementValue(number) 

Example: The following example returns 100, which is 99 incremented by 1:

 #IncrementValue(99)# 

See also Ceiling(), Int(), Round()


InputBaseN()

Description: InputBaseN() converts a string into a number using the base specified. Valid radix values are 236.

Syntax:

 InputBaseN(String, Radix) 

Example: The following example converts the string containing the binary number 10100010 into its base 10 equivalent of 162:

 #InputBaseN("10100010", 2)# 

TIP

The code InputBaseN(String, 10) is functionally equivalent to the code Val(String). If you are converting a number that is base 10, the Val() function is simpler to use.


See also FormatBaseN(), Val()


Insert()

Description: Insert() is used to insert text into a string and takes three parameters. The first parameter, SourceString, is the string you want to insert. The second parameter, TargetString, is the string into which you will insert SourceString. The third parameter, Position, is a numeric value that specifies the location in the TargetString at which to insert the SourceString. Insert() returns the modified string.

Syntax:

 Insert(SourceString, TargetString, Position) 

Example: The following example inserts a field called area code in front of a phone number:

 #Insert(area_code, phone, 0)# 

TIP

To insert a string at the very beginning of another, use the Insert() function specifying a Position of 0.


See also RemoveChars(), SpanExcluding(), SpanIncluding()


Int()

Description: Int() returns the closest integer whose value is less than the numeric parameter. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Int(number) 

Example: The following example returns 99, which is the closest integer less than the parameter value:

 #Int(99.9)# 

The next example returns -100 because -100 is the next integer less than the parameter value.

 #Int(-99.9)# 

See also Ceiling(), Fix(), Round()


IsArray()

Description: IsArray() checks whether a variable is a valid ColdFusion array; it also determines whether an array has a specific number of dimensions. IsArray() takes two parameters: the variable to be checked and an optional number of dimensions to check for. IsArray() returns trUE if the variable is an array and FALSE if not.

Syntax:

 IsArray (Array [, Dimension]) 

Example: The following example checks whether a variable named Users is an array:

 #IsArray(Users)# 

The following example checks whether Users is a three-dimensional array:

 #IsArray(Users, 3)# 

See also ArrayIsEmpty()


IsAuthenticated()

Deprecated.

IsAuthorized()

Deprecated.

IsBinary()

Description: IsBinary() tests whether a specified value is a binary value. Returns TRUE if the specified value is binary and FALSE if it is not. The IsBinary() function takes a single parameter: the value to be evaluated.

Syntax:

 IsBinary(value) 

Example: The following example checks whether a specified value is a binary value:

 #IsBinary(myValue)# 

See also ToBinary(), ToBase64(), IsNumeric()


IsBoolean()

Description: IsBoolean() determines whether a value can be converted to a Boolean value. (Boolean values have two states only, ON and OFF or TRUE and FALSE.) IsBoolean() takes a single parameter: the number, string, or expression to be evaluated. When evaluating numbers, IsBoolean() treats 0 as FALSE and any nonzero value as TRUE.

Syntax:

 IsBoolean(Value) 

Example: The following example checks to see whether a value can be safely converted into a Boolean value before passing it to a formatting function:

 <cfif IsBoolean(status) >  #YesNoFormat(status)# </cfif> 

See also YesNoFormat()


IsCustomFunction()

Description: IsCustomFunction() is used to verify that a function being used is a user-defined function. IsCustomFunction() takes a single parameter: the function to be verified. It returns Yes if the function being evaluated is a user-defined function and No if it is not.

Syntax:

 IsCustomFunction(function) 

Example: The following example checks the function UDF to determine whether it is in fact a user-defined function:

 #IsCustomFunction(UDF)# 

IsDebugMode()

Description: IsDebugMode() checks whether a page is being sent back to the user in debug mode. IsDebugMode() returns trUE if debug mode is on and FALSE if not. IsDebugMode() takes no parameters.

Syntax:

 IsDebugMode() 

Example: The following example writes debug data to a log file if debug mode is on:

 <cfif IsDebugMode()>  <cffile action= "APPEND" file="log.txt" output="#debug_info#"> </cfif> 

IsDefined()

Description: IsDefined() determines whether a specified variable exists. IsDefined() returns trUE if the specified variable exists and FALSE if not. IsDefined() takes a single parameter: the variable for which to check. This parameter can be passed as a fully qualified variable, with a preceding variable type designator. The variable name must be enclosed in quotation marks; otherwise, ColdFusion checks for the existence of the variable's contents rather than of the variable itself.

Syntax:

 IsDefined(Parameter) 

Example: The following example checks whether a variable of any type named USER_ID exists:

 <cfif IsDefined("USER_ID")> 

The next example checks to see whether a CGI variable named USER_ID exists and ignores variables of other types:

 <cfif IsDefined("CGI.USER_ID")> 

NOTE

IsDefined() is a little more complicated than ParameterExists(), but it does enable you to dynamically evaluate and redirect expressions. Because ParameterExists() is a deprecated function, you should always use IsDefined() in its place.


See also Evaluate(), IsSimpleValue()


IsDate

Description: IsDate() checks whether a string contains a valid date; it returns trUE if it does and FALSE if it doesn't. IsDate() takes a single parameter: the string to be evaluated.

Syntax:

 IsDate(String) 

Example: The following example checks whether a user-supplied date string contains a valid date:

 <cfif IsDate(ship_date) IS "No">  You entered an invalid date! </cfif> 

NOTE

IsDate() checks U.S.-style dates only. Use the LSIsDate() function for international date support.


TIP

When specifying the year using the IsDate() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


See also IsLeapYear(), LSIsDate(), ParseDateTime()


IsK2ServerDocCountExceeded()

This function has been deprecated and is no longer in use.

IsK2ServerOnline()

This function has been deprecated and is no longer in use.

IsLeapYear()

Description: IsLeapYear() checks whether a specified year is a leap year. IsLeapYear() takes a single parameter: the year to be checked. It returns trUE if it is a leap year and FALSE if not.

Syntax:

 IsLeapYear(Year) 

Example: The following example checks whether this year is a leap year:

 <cfif IsLeapYear(Year(Now()))>  #Year(Now())# is a leap year <cfelse> #Year(Now())# is not a leap year </cfif> 

TIP

IsLeapYear() takes a year, not a date/time object, as a parameter. To check whether a date stored in a date/time object is a leap year, use the Year() function to extract the year and pass that as the parameter to IsLeapYear().


See also IsDate()


IsNumeric()

Description: IsNumeric() checks whether a specified value is numeric. IsNumeric() takes a single parameter: the value to be evaluated. IsNumeric() returns TRUE if the specified string can be converted to a number and FALSE if it can't.

Syntax:

 IsNumeric(Value) 

Example: The following example checks to ensure that a user has entered a valid age (numeric characters only):

 <cfif IsNumeric(age)>  You entered an invalid age! </cfif> 

NOTE

Use the LSIsNumeric() function for international number support.


See also InputBaseN(), LSIsNumeric(), Val()


IsNumericDate()

Description: IsNumericDate() checks whether a value passed as a date in the ColdFusion internal date format is in fact a legitimate date. IsNumericDate() takes a single parameter: the date to be checked. This date is a floating-point value with precision until the year 9999. IsNumericDate() returns trUE if the passed date value is valid and FALSE if it is not.

Syntax:

 IsNumericDate(Real) 

Example: The following example checks whether a local variable contains a valid date:

 <cfif IsNumericDate(var.target_date)> 

See also IsDate()


IsObject()

Description: The IsObject() function returns true if the specified variable is an object. If it is a basic ColdFusion variable type, the function returns False. Basic ColdFusion variable types include string, integer, float, date, structure, array, query, XML object, and user-defined function. The various object types you can test for are listed in Table C.37. This function can also optionally take component-specific argumentsarguments that differ depending on the type of object you're testing for.

Table C.37. Object Types Used in IsObject

OBJECT TYPES

Component

Java

Corba

Com

Template

Webservice


Syntax:

 IsObject(variable, type, component-specific-param) 

Example: The following example returns a value indicating whether or not it is running inside a component:

 <cfcomponent> <cffunction NAME="tester">  <cfreturn IsObject(this)> </cffunction> </cfcomponent> 

See also CreateObject()


IsProtected()

Deprecated.

IsSimpleValue()

Description: IsSimpleValue() checks whether a value is a string, a number, a trUE/FALSE value, or a Date/Time value. IsSimpleValue() takes a single parameter: the value to be checked. IsSimpleValue() returns trUE if the value is a simple value and FALSE if not.

Syntax:

 IsSimpleValue(Value) 

Example: The following example checks to see that a description field is a simple value:

 <cfif IsSimpleValue(Description)> 

See also Evaluate(), IsDefined()


IsSOAPRequest()

Description: IsSOAPRequest() is invoked inside a ColdFusion component (CFC) function and indicates whether the CFC is being invoked as a Web Service. If it is, IsSOAPRequest() returns True. This function does not take any parameters.

Syntax:

 IsSOAPRequest() 

Example: The example for AddSOAPResponseHeader() includes an example of the usage of IsSOAPRequest().

See also AddSOAPRequestHeader(), AddSOAPResponseHeader(), GetSOAPRequest(), GetSOAPRequestHeader(),GetSOAPResponse(), GetSOAPResponseHeader(),


IsStruct()

Description: The IsStruct() function returns TRUE if the variable being evaluated is a structure. The IsStruct() function takes a single parameter: the variable to be evaluated.

Syntax:

 IsStruct(variable) 

Example: The following example checks to see whether the variable People is a structure:

 #IsStruct(People)# 

IsQuery()

Description: IsQuery() checks whether a variable is a valid ColdFusion query. IsQuery() takes a single parameter: the variable to be checked. IsQuery() returns trUE if the variable is a query and FALSE if not.

Syntax:

 IsQuery(Query) 

Example: The following example checks whether a variable named Users is a query:

 <cfif IsQuery(Users)> 

TIP

IsQuery() is particularly useful within custom tags that expect queries as parameters. IsQuery() can be used to check that a valid value was passed before any processing occurs.


See also QueryAddRow()


IsUserInRole()

Description: IsUserInRole() is part of ColdFusion's security framework and works in conjunction with the use of other parts of the framework. IsUserInRole() checks the current authenticated user's roles, looking for the role specifed in the parameter, role.

NOTE

Note that the user must have been authenticated through use of the <cfloginuser> tag, which along with <cflogin> and <cflogout> is part of the ColdFusion security framework. <cfloginuser> enables you to indicate that the user is part of a role (which you define: Managers, Staff, Admin, and so on).


Syntax:

 IsUserInRole(role) 

Example: The following example checks the current authenticated user to see if he or she is in the Managers role and provides different content based on return value.

 <cfif IsUserInRole("Managers")>  <cfinclude template="FinancialReport.cfm"> <cfelse>  <p>Access denied. </cfif> 

See also QueryAddRow()


IsWDDX()

Description: IsWDDX() checks whether a variable contains a valid WDDX packet. IsWDDX() takes a single parameter: the variable to be checked. IsWDDX() returns trUE if the variable contains a valid packet and FALSE if not.

Syntax:

 IsWDDX(Query) 

Example: The following example checks whether a variable named stream is a valid WDDX packet:

 <cfif IsWDDX(stream)> 

TIP

IsWDDX() should be used to verify a WDDX packet before passing it to <cfwddx>.


IsXML()

Description: IsXML() takes a single parameter (a string) and returns TRue or False indicating whether or not the string represents well-formed XML. Note, the parameter is not an XML object; it's just text string.

Syntax:

IsXML(String)

Example: In the following example, IsXML() returns false, as the XML string is missing a closing </name> tag:

 <cfset xmlString='<contact >   <name first="Joe" last="Shmo">     <phone >333-232-2322</phone>     <phone >333-222-1121</phone> </contact>' > <cfset goodXML=IsXML(xmlString)> <cfoutput>#goodXML#</cfoutput> 

See also IsXMLDoc()


IsXmlAttribute()

Description: This function takes one parameter and indicates whether or not it is an attribute node in an XML DOM. It must be a node in which the XMLType value is Attribute. Note that the XMLSearch() function does return XML DOM attributes.

Syntax:

 IsXMLAttribute(DOM attribute) 

Example: The IsXMLAttribute() function will return false here because, we're only passing it a variable, not an actual part of an XML DOM.

 <cfxml variable="myContact"> <contact >   <name first="Joe" last="Shmo">     <phone >333-232-2322</phone>     <phone >333-232-2321</phone>   </name> </contact> </cfxml> <cfoutput>#IsXMLAttribute(myContact.contact.XmlAttributes.id)#</cfoutput> 

See also IsXMLNode()


IsXMLDoc()

Description: IsXMLDoc() indicates whether the parameter value is a valid ColdFusion XML document object. Returns trUE if it is and FALSE if it is not.

NOTE

Note that the ColdFusion XML document object was introduced starting with ColdFusion MX.


Syntax:

 IsXMLDoc(document) 

Example: The following example checks whether a variable named myXMLDoc is a valid XML document object:

 <!--- Create an ColdFusion XML doc object ---> <cfxml variable="myXMLdoc"> <orders>  <order order   orderdate="3/1/2001"   shipaddress="1 Rue Street"   shipcity="Brussels"   shipzip="1234"  shipstate="">  <orderitem orderitem   item  orderqty="2"  itemprice="30.00"/>  <orderitem orderitem   item  orderqty="1"  itemprice="17.50"/>  <orderitem orderitem  item  orderqty="1"  itemprice="100.00"/>  </order>  <order order  orderdate="3/1/2001"  shipaddress="21700 Northwestern Hwy"  shipcity="Southfield"  shipzip="48075"  shipstate="Michigan">  <orderitem orderitem  item  orderqty="10"  itemprice="7.50"/>  </order> </orders> </cfxml> <!--- Test to make sure it worked ---> <cfif IsXMLDoc(myXMLdoc)>  <p><cfoutput>#IsXMLRoot("orderitem")#</cfoutput> <cfelse>  <cfabort showerror="This is not a vaild XML document object"> </cfif> 

See also IsXML()


IsXMLElem()

Description: IsXMLElem() returns trUE or FALSE to indicate whether the parameter is an XML document object element.

Syntax:

 IsXMLElem(XML_element) 

Example: The following example reads an XML document file into a text variable. This is then parsed into an XML document object. The elements of this document object are split into an array using XMLSearch(). Then the array is looped through, to verify that each element is valid.

 <!--- Read XML file into a text variable ---> <cffile action="READ" file="c:\neo\wwwroot\ows\c\orders.xml" variable="myXMLfile"> <!--- Transform it to an XML document object ---> <cfset myXMLdoc = XMLParse(myXMLfile)> <!--- Test to make sure it worked ---> <cfif IsXMLDoc(myXMLdoc)>  <cfscript>  // Create an array of XML document elements  myXMLarray = XMLSearch(myXMLDoc, "/orders/order/orderitem");  // Loop through array  for (i=1;i LTE ArrayLen(myXMLarray); i=i+1) {  // Verify that each is an element  WriteOutput(IsXMLElem(myXMLarray[i]) & "<br />");  }  </cfscript> <cfelse>  <!--- Not a valid XML document object, warn user --->  <cfabort showerror="This is not a vaild XML document object"> </cfif> 

IsXmlNode()

Description: This function takes one parameter and indicates whether or not it is a node in an XML DOM. The function will return True if the parameter you pass it is the document object, an element in the object or an element in the XMLNodes array.

Syntax:

 IsXMLnode(DOM node) 

Example: The IsXMLNode() function will return true here.

 <cfxml variable="myContact"> <contact >   <name first="Joe" last="Shmo">     <phone >333-232-2322</phone>     <phone >333-232-2321</phone>   </name> </contact> </cfxml> <cfoutput>#IsXmlnode(myContact.contact.name.phone)#</cfoutput>  

See also IsXMLAttribute()


IsXMLRoot()

Description: IsXMLRoot() returns TRUE or FALSE indicating whether the parameter is the root element of an XML document object.

Syntax:

 IsXMLRoot(XML_element_name) 

Example: See the example for IsXMLDoc() above.

See also IsXMLDoc()


JavaCast()

Description: The JavaCast() function is used to indicate that a ColdFusion variable should be converted to be passed as an argument to an overloaded method of a Java object. The JavaCast() function should be used only to pass scalar and string arguments. This function takes two parameters. The first is the data type the variable should be converted to prior to being passed. Possible valid data types are Boolean, int, long, float, double, string and null. The second parameter is the variable to be converted.

Syntax:

 JavaCast(type, variable) 

Example: The following example converts the specified variable to the int data type:

 #JavaCast("int", myNum)# 

See also CreateObject(), CFOBJECT()


JSStringFormat()

Description: The JSStringFormat() function formats a specified string so that it is safe to use with JavaScript. The JSStringFormat() function takes a single parameter: the string to be formatted. The function escapes any special JavaScript characters, so you can put these characters in strings that you pass as JavaScript. The characters that are escaped by the JSStringFormat() function include the ' (single quotation mark), " (double quotation mark), and new-line characters.

Syntax:

 JSStringFormat(string) 

Example: The following example converts the specified string to a format that is safe to use with JavaScript:

 #JSStringFormat("mystring")# 

LCase()

Description: LCase() converts a string to lowercase. LCase() takes a single parameterthe string to be convertedand returns the converted string.

Syntax:

 LCase(String) 

Example: The following example converts a user-supplied string to lowercase:

 #LCase(string_field)# 

See also UCase()


Left()

Description: Left() returns the specified leftmost characters from the beginning of a string. Left() takes two parameters: the string from which to extract the characters and the number of characters to extract.

Syntax:

 Left(String, Count) 

Example: The following example returns the first three characters of a phone number column:

 #Left(phone_number, 3)# 

See also Find(), Mid(), RemoveChars(), Right()


Len()

Description: Len() returns the length of a specified string. Len() takes a single parameter: the string whose length you want to determine.

Syntax:

 Len(String) 

Example: The following example returns the length of a user-supplied address field after it has been trimmed:

 #Len(Trim(address))# 

See also ToBinary(), Left(), Mid(), Right()


ListAppend()

Description: ListAppend() adds an element to the end of a list and returns the new list with the appended element. ListAppend() takes two parameters: the first is the current list, and the second is the element to be appended.

Syntax:

 ListAppend(List, Element) 

Example: The following example appends John to an existing list of users and replaces the old list with the new one:

 <cfset Users = ListAppend(Users, "John")> 

See also ListInsertAt(), ListPrepend(), ListSetAt()


ListChangeDelims()

Description: ListChangeDelims() returns a passed list reformatted to use a different delimiter. ListChangeDelims() takes two parameters: the first is the list to be reformatted, and the second is the new delimiter character.

Syntax:

 ListChangeDelims(List, Delimiter) 

Example: The following example creates a new list containing the same elements as the original list but separated by plus signs:

 <cfset URLUsers = ListChangeDelims(Users, "+")> 

TIP

The default list delimiter, a comma, is the delimiter that SQL lists use. If you are going to pass ColdFusion lists to SQL statements, you should use the default delimiter.


See also ListFirst(), ListQualify()


ListContains()

Description: The ListContains() function performs a case-sensitive search through a list to find the first element that contains the specified search text. If the search text is found, the position of the element containing the text is returned. If no match is found, 0 is returned. It takes two parameters: the first parameter is the list to be searched, and the second parameter is the value for which to search.

Syntax:

 ListContains(List, Value) 

Example: The following example returns the position of the first element that contains the text cash:

 Element #ListContains(Payments, "cash")# contains the word "cash" 

NOTE

ListContains() finds substrings within elements that match the specified search text. To perform a search for a matching element, use the ListFind()function instead.


See also ListContainsNoCase(), ListFind(), ListFindNoCase()


ListContainsNoCase()

Description: The ListContainsNoCase() function performs a noncase-sensitive search through a list to find the first element that contains the specified search text. If the search text is found, the position of the element containing the text is returned. If no match is found, 0 is returned. It takes two parameters: the first parameter is the list to be searched, and the second parameter is the value for which to search.

Syntax:

 ListContainsNoCase(List, Value) 

Example: The following example returns the position of the first element that contains the text cash (regardless of case):

 Element #ListContainsNoCase(Payments, "cash")# contains the word "cash" 

NOTE

ListContainsNoCase() finds substrings within elements that match the specified search text. To perform a search for a matching element, use the ListFindNoCase() function instead.


See also ListContains(), ListFind(), ListFindNoCase()


ListDeleteAt()

Description: ListDeleteAt() deletes a specified element from a list. ListDeleteAt() takes two parameters: the first is the list to be processed, and the second is the position of the element to be deleted. ListDeleteAt() returns a modified list with the specified element deleted. The specified element position must exist; an error message is generated if you specify an element beyond the range of the list.

Syntax:

 ListDeleteAt(List, Position) 

Example: The following example deletes the second element in a list, but it first verifies that it exists:

 <cfif #ListLen(Users)# GTE 2>  <cfset Users = ListDeleteAt(Users, 2)> </cfif> 

See also ListRest()


ListFind()

Description: The ListFind() function performs a case-sensitive search through a list to find the first element that matches the specified search text. If a matching element is found, the position of that element is returned; if no match is found, 0 is returned. It takes two parameters: the first parameter is the list to be searched, and the second parameter is the element text to search for.

Syntax:

 ListFind(List, Value) 

Example: The following example returns the position of the first element whose value is MI:

 MI is element #ListFind(States, "MI")# 

NOTE

ListFind()finds only elements that exactly match the specified search text. To perform a search for substrings within elements, use the ListContains() function.


See also ListContains(), ListContainsNoCase(), LindFindNoCase()


ListFindNoCase()

Description: The ListFindNoCase() function performs a noncase-sensitive search through a list to find the first element that matches the specified search text. If a matching element is found, the position of that element is returned; if no match is found, 0 is returned. It takes two parameters: the first parameter is the list to be searched, and the second parameter is the element text for which to search.

Syntax:

 ListFindNoCase(List, Value) 

Example: The following example returns the position of the first element whose value is MI, regardless of case:

 MI is element #ListFindNoCase(States, "MI")# 

NOTE

ListFindNoCase() finds only elements that exactly match the specified search text. To perform a search for substrings within elements, use the ListContainsNoCase()function.


See also ListContains(), ListContainsNoCase(), ListFind()


ListFirst()

Description: ListFirst() returns the first element in a list. ListFirst() takes a single parameter: the list to be processed.

Syntax:

 ListFirst(List) 

Example: The following example returns the first selection from a field of book titles submitted by a user:

 The first title you selected is #ListFirst(titles)# 

See also ListGetAt(), ListLast(), ListRest()


ListGetAt()

Description: ListGetAt() returns the list element at a specified position. ListGetAt() takes two parameters: The first is the list to process, and the second is the position of the desired element. The value passed as the position parameter must not be greater than the length of the list; otherwise, a ColdFusion error message is generated.

Syntax:

 ListGetAt(List, Position) 

Example: The following example returns the name of the fourth selection from a field of book titles submitted by a user:

 The fourth title you selected is #ListGetAt(titles, 4)# 

See also ListFirst(), ListLast(), ListRest()


ListInsertAt()

Description: ListInsertAt() inserts a specified element into a list, shifting all elements after it one position to the right. ListInsertAt() takes three parameters: The first is the list to be processed; the second is the desired position for the new element; and the third is the value of the new element. The position parameter must be no greater than the number of elements in the list. A ColdFusion error message is generated if a greater value is provided.

Syntax:

 ListInsertAt(List, Position, Value) 

Example: The following example inserts John into the third position of an existing list of users and replaces the old list with the new one:

 <cfset Users = #ListInsertAt(Users, 3, "John")#> 

See also ListAppend(), ListPrepend(), ListSetAt()


ListLast()

Description: ListLast() returns the last element in a list. ListLast() takes a single parameter: the list to be processed.

Syntax:

 ListLast(List) 

Example: The following example returns the last selection from a field of book titles submitted by a user:

 The last title you selected is #ListLast(titles)# 

See also ListFirst(), ListGetAt(), ListRest()


ListLen()

Description: ListLen() returns the number of elements present in a list. ListLen() takes a single parameter: the list to be processed.

Syntax:

 ListLen(List) 

Example: The following example returns the number of books selected by a user:

 You selected #ListLen(titles)# titles 

See also ListAppend(), ListDeleteAt(), ListInsertAt(), ListPrepend()


ListPrepend()

Description: ListPrepend() inserts an element at the beginning of a list, pushing any other elements to the right. ListPrepend() returns the new list with the prepended element. ListPrepend() takes two parameters: The first is the current list, and the second is the element to be prepended.

Syntax:

 ListPrepend(List, Element) 

Example: The following example prepends John to an existing list of users and replaces the old list with the new one:

 <cfset Users = ListPrepend(Users, "John")> 

See also ListAppend(), ListInsertAt(), ListSetAt()


ListSort()

Description: ListSort() sorts the items in a list according to the specified sort type and order. The ListSort() function takes four parameters. The first, list, specifies the list you want to sort. The second, sort_type, specifies the type of sort you want to perform. Valid sort types are Numeric (which sorts numerically), Text (which sorts alphabetically), and TextNoCase (which sorts alphabetically without regard to case). The third parameter, sort_order, is optional. You can specify either ASC (ascending) or DESC (descending). When no sort order is chosen, ascending order is used. The fourth parameter, delimiter, specifies the character to use to delimit items in the list. This parameter is also optional. If no delimiter is provided, a comma is used by default.

Syntax:

 ListSort(list, sort_type [, sort_order] [, delimiter ]) 

Example: The following example sorts a list with the TextNoCase sort type. By default, the list items are returned in ascending order, with a comma delimiting items in the list:

 #ListSort(JohnList, "TextNoCase")# 

ListToArray()

Description: ListToArray() converts a ColdFusion list to a one-dimensional array. ListToArray() takes two parameters: the list to be converted and an optional list delimiter. If no delimiter is specified, the default (comma) delimiter is used. ListToArray() creates a new array.

Syntax:

 ListToArray(List [, Delimiter]) 

Example: The following example converts a list of users into an array:

 <cfset UserArray = #ListToArray(UserList)#> 

CAUTION

When evaluating a list, ColdFusion will ignore any empty items in a list. If you have a list defined as "Laura, John, Sean, , ,Bryan", it will be evaluated as a four-element list, not a six-element list.


See also ArrayToList()


ListQualify()

Description: The ListQualify() function returns the contents of a specified list with qualifying characters around each list item. The ListQualify() function takes four parameters. The first parameter is the list you want to parse through. The second parameter is the qualifying character you want to have placed around each list item. The third parameter is the delimiter used in the list you are evaluating. The fourth is whether you want to evaluate every list item or only the list items composed of alphabetic characters. You specify this by defining the elements parameter as either ALL or CHAR.

Syntax:

 ListQualify(list, qualifier [, delimiters ] [, elements ]) 

Example: The following example looks through the elements of a list that is delimited with a comma, placing double quotation marks around all list items, regardless of whether the list item is numeric or composed of alphabetic characters:

 #ListQualify(JohnList,"""",",","ALL")#  

ListRest()

Description: ListRest() returns a list containing all the elements after the first element. If the list contains only one element, an empty list (an empty string) is returned. ListRest() takes a single parameter: the list to be processed.

Syntax:

 ListRest(List) 

Example: The following example replaces a list with the list minus the first element:

 <cfset Users = ListRest(Users)> 

See also ListDeleteAt()


ListSetAt()

Description: ListSetAt() replaces the value of a specific element in a list with a new value. ListSetAt() takes four parameters: The first is the list to be processed; the second is the position of the element to be replaced; the third is the new value; and the fourth is the delimiter or set of delimiters to use. If more than one delimiter is specified, ColdFusion defaults to the first delimiter in the list. If no delimiter is specified, the delimiter defaults to a comma. The value passed to the position parameter must be no greater than the number of elements in the list; otherwise, a ColdFusion error message is generated.

Syntax:

 ListSetAt(List, Position, Value [, delimiters]) 

Example: The following example searches for an element with the value of "Honda" and replaces it with the value "Harley":

 <cfif ListFindNoCase(Users, "Honda") GT 0>  <cfset Users = ListSetAt(Users, ListFindNoCase(Users, "Honda"), "Harley")> </cfif> 

See also ListAppend(), ListInsertAt(), ListPrepend()


ListValueCount()

Description: ListValueCount() searches a list for a specific value and returns the number of occurrences it finds of the specified value. The ListValueCount() function is case-sensitive. It takes three parameters. The first parameter is the list to search; the second parameter is the value for which to search the list. The third, optional parameter is the character used to delimit elements in the specified list. If the delimiter parameter is omitted, the default comma is used.

Syntax:

 ListValueCount(list, value [, delimiters ]) 

Example: The following example searches through a list of users to see how many have the first name Laura:

 #ListValueCount(usersList, "Laura")# 

See also ListValueCountNoCase()


ListValueCountNoCase()

Description: ListValueCountNoCount() performs a non-case-sensitive search of a list for a specific value and returns the number of occurrences it finds of the specified value. It takes three parameters. The first parameter is the list to search; the second parameter is the value for which to search the list. The third, optional parameter is the character used to delimit elements in the specified list. If the delimiter parameter is omitted, the default comma is used.

Syntax:

 ListValueCountNoCase(list, value [, delimiters ]) 

Example: The following example searches through a list of users to see how many have the first name Laura:

 #ListValueCountNoCase(usersList, "laura")# 

See also ListValueCount()


LJustify()

Description: LJustify() left-aligns a string within a field of a specified length. It does this by padding spaces after the specified text. LJustify() takes two parameters: the string to process and the desired string length.

Syntax:

 #LJustify(String, Length)# 

Example: The following example left-justifies the string "First Name:" so that it is left-aligned within a 25-character-wide field:

 #LJustify("First Name:", 25)# 

See also CJustify(), LTrim(), RJustify(), RTrim(), Trim()


Log()

Description: Log() returns the natural logarithm of a passed number. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Log(number) 

Example: The following example returns 1.60943791243, the natural logarithm of 5:

 #Log(5)# 

See also Log10(), Exp()


Log10()

Description: Log10() returns the base 10 log of a passed number. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Log10(number) 

Example: The following example returns 0.698970004336, the natural logarithm of 5:

 #Log10(5)# 

See also Log(), Exp()


LSCurrencyFormat()

Description: LSCurrencyFormat() displays currency information formatted for the current locale. LSCurrencyFormat() takes two parameters: the number to display and an optional format type. If a type is specified, its value must be none, local, or international. Type defaults to none.

Syntax:

 LSCurrencyFormat(Number [, Type]) 

Example: The following example displays the results of an equation (quantity multiplied by item cost) in formatting appropriate for the French locale:

 <cfset previous_locale = SetLocale("French (Standard)")> Total cost: #LSCurrencyFormat(quantity*item_cost)# 

NOTE

Unlike versions of ColdFusion prior to ColdFusion MX, the locales used for formatting are now defined by Java standard locale formatting rules on all platforms.


TIP

For more precise currency display, use the NumberFormat() function instead.


NOTE

You can use the simpler DollarFormat() function for U.S. currency formatting.


See also DollarFormat(), NumberFormat()


LSDateFormat()

Description: LSDateFormat() displays the date portion of a date/time object in a readable format. LSDateFormat() is the locale-specific version of the DateFormat() function. Similar to DateFormat(), LSDateFormat() takes two parameters: the first is the date/time object to be displayed, and the second is an optional mask value enabling you to control exactly how the data is formatted. If no mask is specified, a format suitable for the current locale is used. The complete set of date masks is listed in the DateFormat() section.

Syntax:

 LSDateFormat(Date [, mask ]) 

Example: The following example displays today's date with the default formatting options for the current locale:

 Today is: #LSDateFormat(Now())# 

The next example displays the same date but uses the current locale's full names of both the day of week and the month:

 It is #LSDateFormat(Now(), "DDDD, MMMM DD, YYYY")# 

NOTE

Unlike versions of ColdFusion prior to ColdFusion MX, the locales used for formatting are now defined by Java standard locale formatting rules on all platforms.


NOTE

You can use the simpler DateFormat() function for U.S. dates.


See also DateFormat(), LSNumberFormat(), LSTimeFormat()


LSEuroCurrencyFormat()

Description: LSEuroCurrencyFormat() returns a currency value formatted in the convention of the locale enabled on the executing machine, using the euro currency symbol. The LSEuroCurrencyFormat function takes two parameters. The first, currency-value, is the actual amount or value of the currency you want to format. The second parameter, type, is an optional parameter that enables you to specify a currency type of none, local, or international. If no currency type is specified, the default of local is used. Depending on which type you choose, ColdFusion will display the value with differing currency symbols. If none is chosen, the value is displayed as a simple numeric value. If local is chosen, the value is displayed in the convention of the locale that is set on the executing machine, displaying the symbol for the euro if an accommodating character set is installed. If international is chosen, then the value is displayed with EUR, the international symbol for the euro.

Syntax:

 LSEuroCurrencyFormat(currency-value [,type]) 

NOTE

Unlike versions of ColdFusion prior to ColdFusion MX, the locales used for formatting are now defined by Java standard locale formatting rules on all platforms


Example: The following formats the value 70,000 to display as EUR70.000,00, assuming the locale on the current machine is European:

 #LSEuroCurrencyFormat(70000, "international")# 

See also LSParseEuroCurrency(), SetLocale()


LSIsCurrency()

Description: LSIsCurrency() checks whether a string contains a valid currency for the current locale; it returns trUE if it does and FALSE if it does not. LSIsCurrency() takes a single parameter: the string to be evaluated.

Syntax:

 LSIsCurrency(String) 

NOTE

Unlike versions of ColdFusion prior to ColdFusion MX, the locales used for formatting are now defined by Java standard locale formatting rules on all platforms.


Example: The following example checks whether a user-supplied date string contains a valid German currency value:

 <cfset previous_locale = SetLocale("German (Standard)")> <cfif LSIsCurrency(total) IS "No">  You entered an invalid currency amount! </cfif> 

See also IsNumber(), LSIsNumeric()


LSIsDate()

Description: LSIsDate() checks whether a string contains a valid date for the current locale; it returns trUE if it does and FALSE if it does not. LSIsDate() takes a single parameter: the string to be evaluated.

Syntax:

 LSIsDate(String) 

NOTE

Unlike versions of ColdFusion prior to ColdFusion MX, the locales used for formatting are now defined by Java standard locale formatting rules on all platforms.


Example: The following example checks whether a user-supplied date string contains a valid German date:

 <cfset previous_locale = SetLocale("German (Standard)")> <cfif LSIsDate(ship_date) IS "No">  You entered an invalid date! </cfif> 

NOTE

To check U.S. dates, you can use the IsDate() function.


See also IsDate(), IsLeapYear(), LSParseDateTime(), ParseDateTime()


LSIsNumeric()

Description: LSIsNumeric() checks whether a specified value is numeric. LSIsNumeric() is the locale-specific version of the IsNumeric() function. LSIsNumeric() takes a single parameter: the value to be evaluated.

Syntax:

 LSIsNumeric(Value) 

NOTE

Unlike versions of ColdFusion prior to ColdFusion MX, the locales used for formatting are now defined by Java standard locale formatting rules on all platforms.


Example: The following example checks to ensure that a user has entered a valid locale-specific age (numeric characters only):

 <cfif LSIsNumeric(age) IS "No">  You entered an invalid age! </cfif> 

NOTE

You can use the simpler IsNumeric() function for U.S. number support.


See also InputBaseN(), IsNumeric(), Val()


LSNumberFormat()

Description: LSNumberFormat() enables you to display numeric values in a locale-specific, readable format. LSNumberFormat() is the locale-specific version of the NumberFormat function. LSNumberFormat() takes two parameters: the number to be displayed and an optional mask value. If the mask is not specified, the default mask of ,99999999999999 is used. The complete set of number masks is listed in Table C.35 in the description of the NumberFormat() function.

If the mask you use can't format the specified number, this function returns the number unformatted.

Syntax:

 LSNumberFormat(Number [, mask ]) 

NOTE

Unlike versions prior to ColdFusion MX, the locales used for formatting are now defined by Java standard locale formatting rules on all platforms.


NOTE

To display numbers in any of the U.S. formats, you can use the NumberFormat() function.


Example: The following example displays a submitted form field in the default format for the current locale:

 #LSNumberFormat(FORM.quantity)# 

See also DecimalFormat(), DollarFormat(), LSCurrencyFormat(), LSParseNumber(), NumberFormat()


LSParseCurrency()

Description: LSParseCurrency() converts a locale-specific number in string form into a valid number. LSParseCurrency() takes two parameters: the string to be converted and an optional type. If a type is specified, its value must be none, local, or international. Type defaults to all types if not provided.

Syntax:

 LSParseCurrency(String [, Type]) 

NOTE

Unlike versions of ColdFusion prior to ColdFusion MX, the locales used for formatting are now defined by Java standard locale formatting rules on all platforms.


Example: The following example converts a user-supplied currency string into a number:

 <cfset sale_price = LSParseCurrency(FORM.sale_price)> 

See also LSCurrencyFormat(), LSParseNumber()


LSParseDateTime()

Description: LSParseDateTime() converts a locale-specific date in string form into a ColdFusion date/time object. LSParseDateTime() is the locale-specific version of the ParseDateTime() function. LSParseDateTime() takes a single parameter: the string to be converted.

Syntax:

 LSParseDateTime(String) 

NOTE

Unlike versions of ColdFusion prior to ColdFusion MX, the locales used for formatting are now defined by Java standard locale formatting rules on all platforms.


Example: The following example converts a user-supplied string containing a date into a ColdFusion date/time object:

 <cfset ship_date = LSParseDateTime(FORM.ship_date)> 

NOTE

For U.S. dates and times, you can use the simpler ParseDateTime() function.


CAUTION

Unlike the ParseDateTime() function, the LSParseDateTime() function does not support POP date/time fields. Passing a POP date/time field to LSParseDateTime() generates an error.


See also CreateDateTime(), ParseDateTime()


LSParseEuroCurrency()

Description: The LSParseEuroCurrency() function converts a currency string that contains the euro symbol or sign to a number. This function attempts conversion of the string based on all three default currency formats (none, local, and international). This function takes a single parameter: the string to be converted.

Syntax:

 LSParseEuroCurrency(currency-string) 

NOTE

Unlike versions of ColdFusion prior to ColdFusion MX, the locales used for formatting are now defined by Java standard locale formatting rules on all platforms.


Example: The following example converts a currency string in the euro currency format into a simple number:

 #LSParseEuroCurrency("EUR1974")# 

See also LSEuroCurrencyFormat(), LSParseCurrency()


CAUTION

For the LSParseEuroCurrency() function to be able to read the euro currency symbol, the machine running the code must have euro-enabled fonts installed.


LSParseNumber()

Description: LSParseNumber() converts a locale-specific number in string form into a valid number. LSParseNumber() takes a single parameter: the string to be converted.

Syntax:

 LSParseNumber(String) 

NOTE

Unlike versions of ColdFusion prior to ColdFusion MX, the locales used for formatting are now defined by Java standard locale formatting rules on all platforms.


Example: The following example converts a user-supplied numeric string into a number:

 <cfset quantity = LSParseNumber(FORM.quantity)> 

See also LSCurrencyFormat(), LSParseCurrency(), Val()


LSTimeFormat()

Description: LSTimeFormat() displays the time portion of a date/time object in a locale-specific, readable format. LSTimeFormat() is the locale-specific version of the TimeFormat() function. LSTimeFormat() takes two parameters: The first is the date/time object to be displayed, and the second is an optional mask value that enables you to control exactly how the data is formatted. If no mask is specified, a mask appropriate for the current locale is used. The complete set of date masks is listed in Table C.37, in the description of the TimeFormat() function.

Syntax:

 LSTimeFormat(Date [, mask ]) 

NOTE

Unlike versions of ColdFusion prior to ColdFusion MX, the locales used for formatting are now defined by Java standard locale formatting rules on all platforms.


Example: The following example displays the current time with the default formatting options for the current locale:

 The time is: #LSTimeFormat(Now())# 

NOTE

You can use the simpler TimeFormat() function for U.S. times.


See also LSDateFormat(), LSNumberFormat(), TimeFormat()


LTrim()

Description: LTrim() TRims white space (spaces, tabs, and new-line characters) from the beginning of a string. LTrim() takes a single parameter: the string to be trimmed.

Syntax:

 LTrim(String) 

Example: The following example trims spaces from the beginning of a table note field:

 #LTrim(notes)# 

See also CJustify(), LJustify(), RJustify(), RTrim(), Trim(), StripCR()


Max()

Description: Max() returns the greater of two passed numbers. This function takes two numeric values as parameters. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Max(number1, number2) 

Example: The following example returns 2, the greater value of 2 and 1:

 #Max(1, 2)# 

See also Min()


Mid()

Description: Mid() returns a string of characters from any location in a string. Mid() takes three parameters. The first is the string from which to extract the characters; the second is the desired characters' starting position; and the third is the number of characters required.

Syntax:

 Mid(String, StartPosition, Count) 

Example: The following example extracts eight characters from the middle of a table column, starting at position 3:

 #Mid(order_number, 3, 8)# 

See also Find(), Left(), RemoveChars(), Right()


Min()

Description: Min() returns the smaller of two passed numbers. This function takes two numeric values as parameters. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Min(number1, number2) 

Example: The following example returns 1, the smaller value of 2 and 1:

 #Min(1, 2)# 

See also Max()


Minute()

Description: Minute() returns a date/time object's minute as a numeric value with possible values of 059. Minute() takes a single parameter: the date/time object to be processed.

Syntax:

 Minute(Date) 

Example: The following example returns the current time's minutes:

 #Minute(Now())# minutes have elapsed since #Hour(Now())# o'clock 

TIP

When specifying the year using the Minute() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


TIP

Always enclose date/time values in quotes when passing them to the Minute() function as strings. Without quotes, the value passed is interpreted as a numeral representation of a date/time object.


See also Day(), DayOfWeek(), DayOfYear(), Hour(), Month(), Quarter(), Second(), Week(), Year()


Month()

Description: Month() returns a date/time object's month as a numeric value with possible values of 112. Month() takes a single parameter: the date/time object to be processed.

Syntax:

 Month(Date) 

Example: The following example returns the current month:

 It is month #Month(Now())# of year #Year(Now())# 

See also Day(), DayOfWeek(), DayOfYear(), Hour(), Minute(), Quarter(), Second(), Week(), Year()


MonthAsString()

Description: MonthAsString() returns the English month name for a passed month number. MonthAsString() takes a single parameter: the number of the month to be processed, with a value of 112.

Syntax:

 MonthAsString(MonthNumber) 

Example: The following example returns the English name of the current month:

 It is #MonthAsString(Month(Now()))#". 

See also DayOfWeek(), Month()


Now()

Description: Now() returns a date/time object containing the current date and time precisely to the second. Now() takes no parameters.

Syntax:

 Now() 

Example: The following example returns the current date and time formatted for correct display:

 It is now #DateFormat(Now())# #TimeFormat(Now())# 

NOTE

The Now() function returns the system date and time of the computer running the ColdFusion service, not of the system running the Web browser. The date/time object that the Now() function returns can be passed to many other date/time functions.


See also CreateDateTime(), DatePart()


NumberFormat()

Description: NumberFormat() enables you to display numeric values in a readable format. NumberFormat() takes two parameters: the number to be displayed and an optional mask value. If the mask is not specified, the default mask of ",99999999999999" is used. The complete set of number masks is listed in Table C.38.

Table C.38. NumberFormat() Mask Characters

MASK

DESCRIPTION

_

Optional digit placeholder

9

Optional digit placeholder (same as _ but shows decimal place more clearly)

.

Specifies the location of the decimal point

0

Forces padding with 0s

()

Displays parentheses around the number if it is less than 0

+

Displays a plus sign in front of positive numbers and a minus sign in front of negative numbers

-

Displays a minus sign in front of negative numbers and leaves a space in front of positive numbers

,

Separates thousands with commas

C

Centers the number within mask width

L

Left-justifies the number within mask width

$

Places a dollar sign in front of the number

^

Specifies the location for separating left and right formatting


Syntax:

 NumberFormat(Number [, mask ]) 

Example: To demonstrate how the number masks can be used, Table C.39 lists examples of various masks being used to format the numbers 1453.876 and 1453.876.

Table C.39. Number Formatting Examples

MASK

RESULT

NOTES

NumberFormat(1453.876,

1454

No decimal point is specified in the "9999") mask, so the number is rounded to the nearest integer value.

NumberFormat(-1453.876,

1454

No decimal point is specified in the "9999") mask, so the number is rounded to the nearest integer value.

NumberFormat(1453.876,

1453.88

Even though a decimal point is "9999.99") provided, the number of decimal places specified is less than needed; the decimal portion must be rounded to the nearest integer value.

NumberFormat(1453.876,

1453.88

The number is positive, so the "(9999.99)") parentheses are ignored.

NumberFormat(-1453.876,

(1453.88)

The number is negative, so "(9999.99)") parentheses are displayed around the number.

NumberFormat(1453.876,

1453.88

The number is positive, so the "-9999.99") minus sign is ignored.

NumberFormat(-1453.876,

-1453.88

The number is negative, so "-9999.99")a minus sign is displayed.

NumberFormat(1453.876,

+1453.88

The number is positive, so a "+9999.99")plus sign is displayed.

NumberFormat(-1453.876,

-1453.88

The number is negative, so a "+9999.99")minus sign is displayed.

NumberFormat(1453.876,

$1453.88

Using the dollar sign as the first "$9999.99") character of the mask places a dollar sign at the beginning of the output.

NumberFormat(1453.876,

1453.876

Position six of the mask is a carat "C99999^9999") character, so the decimal point is positioned there even though fewer than six digits appear before the decimal point. This enables you to align columns of numbers at the decimal point.


NOTE

Use the LSNumberFormat()function for international number support.


See also DecimalFormat(), DollarFormat(), LSNumberFormat()


ParagraphFormat()

Description: ParagraphFormat() converts text with embedded carriage returns for correct HTML display. HTML ignores carriage returns in text, so they must be converted to HTML paragraph markers (the <p> tag) to be displayed correctly. ParagraphFormat() takes a single parameter: the text to be processed.

Syntax:

 ParagraphFormat(Text) 

Example: The following example displays a converted text file inside a form <textarea> field:

 <textarea name="comments">#ParagraphFormat(comments)#</textarea> 

TIP

ParagraphFormat() is useful for displaying data in FORM TEXTAREA fields.


See also HTMLCodeFormat(), HTMLEditFormat()


ParameterExists()

Deprecated.

ParseDateTime()

Description: ParseDateTime() converts a date in string form into a ColdFusion date/time object. ParseDateTime() takes two parameters: the string to be converted and, if specified, the POP conversion method. When a POP conversion method (POP or STANDARD) is specified, this function parses the date/time string passed from a POP mail server.

Syntax:

 ParseDateTime(String)# or #ParseDateTime(String [,pop-conversion method]) 

NOTE

When using the ParseDateTime() function with a POP conversion method, one of two POP conversion methods can be specified. The first of these methods, POP, converts the date/time string passed from a POP mail server to GMT for the U.S. locale. The second POP conversion method available, STANDARD, provides no conversion on the date/time string passed and simply returns the time string as it was retrieved from the POP mail server.


Example: The following example converts a user-supplied string containing a date into a ColdFusion date/time object:

 <cfset ship_date = ParseDateTime(FORM.ship_date) > 

NOTE

ParseDateTime() supports U.S.-style dates and times only. Use the LSParseDateTime() function for international date and time support.


See also CreateDateTime(), LSParseDateTime()


Pi()

Description: Pi() returns the value of Pi as 3.14159265359. It takes no parameters.

Syntax:

 Pi() 

Example: The following example displays the value of pi:

 Pi equals #Pi()#. 

See also Asin(), Cos(), Sin(), Tan()


PreserveSingleQuotes()

Description: PreserveSingleQuotes() instructs ColdFusion to not escape single quotation marks contained in values derived from dynamic parameters. PreserveSingleQuotes() takes a single parameter: the string to be preserved. This function is particularly useful when you are constructing SQL statements that will contain ColdFusion variables.

Syntax:

 PreserveSingleQuotes(String) 

Example: The following example uses PreserveSingleQuotes() to ensure that a dynamic parameter in a SQL statement is included correctly:

 SELECT * FROM Customers WHERE CustomerName IN ( #PreserveSingleQuotes(CustNames)#) 

Quarter()

Description: Quarter() returns a date/time object's quarter as a numeric value with possible values of 14. Quarter() takes a single parameter: the date/time object to be processed.

Syntax:

 Quarter(Date) 

Example: The following example returns the current quarter:

 We are in quarter #Quarter(Now())# of year #Year(Now())# 

TIP

When specifying the year using the Quarter() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


TIP

Always enclose date/time values in quotes when passing them to the Quarter() function as strings. Without quotes, the value passed is interpreted as a numeral representation of a date/time object.


See also Day(), DayOfWeek(), DayOfYear(), Hour(), Minute(), Month(), Second(), Week(), Year()


QueryAddColumn()

Description: QueryAddColumn() adds a new column to a specified query and populates that column with data from a one-dimensional array. The number of the column that was added is returned. If necessary, the contents of other query columns are padded to ensure that all columns retain the same number of rows. The QueryAddColumn() function takes up to four parameters. The first is the name of the query to which you want to add a column. The second is the name of the new column you are about to create. The third parameter is optional and enables you to identify the data type of the column. You can choose from any of the types described in Table C.40. The fourth is the name of the array that will be used to populate the query column.

Table C.40. Data Types Used To Create Query Columns

DATA TYPE

DESCRIPTION

Integer

32-bit integer

BigInt

64-bit integer

Double

64-bit decimal number

Decimal

Variable length decimal as specified by java.math.BigDecimal

Varchar

String

Binary

Byte array

Bit

Boolean value of 1 or 0

Time

Time value

Date

Date value (which can include a time value as well)


Syntax:

 QueryAddColumn(query, column-name[, datatype], array-name) 

Example: The following example creates a new column called UserName in the query GetUsers and updates that column with the data contained in the UserNameArray array:

 #QueryAddColumn(qGetUsers, "UserName", UserNameArray)#> 

TIP

When using the QueryAddColumn() function, remember that you can't add columns to cached queries.


See also QueryNew(), <cfquery>, QueryAddRow()


QueryAddRow()

Description: QueryAddRow() adds a row to an existing ColdFusion query. QueryAddRow() takes two parameters: the query to which to add a row and an optional number of rows to add. If the number of rows is omitted, the default number of 1 is used.

Syntax:

 QueryAddRow(Query [, Number]) 

Example: The following example creates a new query called Users and adds 10 rows to it:

 <cfset Users = QueryNew("FirstName, LastName")> <cfset temp = QueryAddRow(Users, 10)> 

See also QueryNew(), QuerySetCell()


QueryNew()

Description: QueryNew() either returns an empty query with a user-defined set of columns, as specified with the columnlist argument. You can optionally specify data types for the columns with a list of data types. The data types can be any of those found in Table C.40. If an empty string is specified in the columnlist argument, it returns an empty query with no columns.

Syntax:

 QueryNew( columnlist[,columneTypeList]) 

Example: The following example creates a new query called Users with columns for FirstName and LastName:

 <cfset Users = QueryNew("FirstName, LastName", "Varchar, Varchar")> <cfset temp = QueryAddRow(Users, 10)> 

See also QueryAddRow(), QuerySetCell()


QuerySetCell()

Description: QuerySetCell() is used to set the values of specific cells in a table. QuerySetCell() takes four parameters: the query name, the column name, the value, and an optional row number. If the row number is omitted, the cell in the last query row is set.

Syntax:

 QuerySetCell(Query, Column, Value [, Row]) 

Example: The following example sets the FirstName column in the third row to the value Ben:

 <cfset temp = QuerySetCell(Users, "FirstName", "John", 3)> 

NOTE

Query cells can also be set using the <cfset> tag, treating the query as a two-dimensional array.


See also QueryAddRow(), QueryNew()


QuotedValueList()

Description: QuotedValueList() drives one query with the results of another. It takes a single parameterthe name of a query columnand return a list of all the values in that column. QuotedValueList() returns a list of values that are each enclosed within quotation marks and separated by commas.

Syntax:

 QuotesValueList(Column) 

Example: The following example passes the results from one query to a second query:

 SELECT * FROM Customers WHERE CustomerType IN (#QuotedValueList(CustType.type)#) 

NOTE

The QuotedValueList()function is typically used only when constructing dynamic SQL statements.


TIP

The values returned by QuotedValueList() is in the standard ColdFusion list format and can therefore be manipulated by the list functions.


TIP

As a general rule, you should always try to combine both of the queries into a single SQL statement, unless you need to manipulate the values in the list. The time it takes to process one combined SQL statement is far less than the time it takes to process two simpler statements.


See also ValueList()


Rand()

Description: Rand() takes one optional parameter, algorithm, and returns a random number between 0 and 1. The algorithm parameter can be one of the following values: CFMX_COMPAT, SHA1PRNG, IBMSecureRandom. CFMX_COMPAT is the default and will cause Rand() to mimic the behavior of ColdFusion MX and earlier versions. SHA1PRNG uses the Sun Java algorithm of the same name, and IBMSecureRandom is for use on WebSphere servers.

Syntax:

 Rand([algorithm]) 

Example: The following example returns a random number:

 #Rand("SHA1PRNG")# 

See also Randomize(), RandRange()


Randomize()

Description: Randomize() seeds the random number generator with the passed number. This function takes a numeric value as a parameter and enables you to optionally indicate a specific algorithm to use when generating a random number. The number parameter must be an integer in the range-2,147,483,648 to 2,147,483,647.

The algorithm parameter can be one of the following values: CFMX_COMPAT, SHA1PRNG, IBMSecureRandom. CFMX_COMPAT is the default and will cause Randomize() to mimic the behavior of ColdFusion MX and earlier versions. SHA1PRNG uses the Sun Java algorithm of the same name, and IBMSecureRandom is for use on WebSphere servers.

Syntax:

 Randomize(number[,algorithm]) 

Example: The following example returns 0.57079106, a random number that was seeded with 5:

 #Randomize(5)# 

See also Rand(), RandRange()


RandRange()

Description: RandRange() returns a random integer value between the two passed numbers. This function requires two numeric parameters and enables you to optionally specify the randomization algorithm. You can pass real values, integer values, and ColdFusion fields to this function.

The algorithm parameter can be one of the following values: CFMX_COMPAT, SHA1PRNG, IBMSecureRandom. CFMX_COMPAT is the default and will cause Randomize() to mimic the behavior of ColdFusion MX and earlier versions. SHA1PRNG uses the Sun Java algorithm of the same name, and IBMSecureRandom is for use on WebSphere servers.

Syntax:

 RandRange(number1, number2[,algorithm]) 

Example: The following example returns a random integer value between 5 and 10, just as it would have been produced in ColdFusion MX or earlier:

 #RandRange(5, 10, "CFMX_COMPAT")# 

See also Randomize(), Rand()


REFind()

Description: REFind() performs a case-sensitive search using regular expressions. The first parameter is the string (or regular expression) for which to search, and the second parameter is the target string, or string to be searched. The third, optional parameter can specify the position in the target string from which to start the search. All of these functions return the starting position of the first occurrence of the search string within the specified target string. If the search string is not found, 0 is returned.

Syntax:

 REFind(RegularExpression, TargetString [, StartPosition]) 

Example: The following example returns 2, the position of the first vowel:

 #REFind("[aeiou]", "somestring", "1")# 

TIP

Regular expressions enable you to perform complex searches through text strings with relative ease. Rather than forcing you to provide the exact text for which you are searching, using the REFind and REFindNoCase functions gives you the flexibility of searching for dynamic data. Suppose you wanted to search a string for the first occurrence of any character except vowels. In this case, using REFindNoCase would make your job much easier.


See also REFindNoCase(), FindOneOf(), GetToken(), Left(), Mid(), Right()


REFindNoCase()

Description: REFindNoCase() performs a non-case-sensitive search using regular expressions. The first parameter is the string (or regular expression) for which to search, and the second parameter is the target string, or string to be searched. The third, optional parameter can specify the position in the target string from which to start the search. All these functions return the starting position of the first occurrence of the search string within the specified target string. If the search string is not found, 0 is returned.

Syntax:

 REFindNoCase(RegularExpression, TargetString [, StartPosition]) 

Example: The following example returns 2, the position of the first o:

 #REFindNoCase("[O]", "somestring", "1")# 

TIP

Regular expressions enable you to perform complex searches through text strings with relative ease. Rather than forcing you to provide the exact text for which you are searching, using the REFindNoCase() function gives you the flexibility of searching for dynamic data. Suppose you wanted to search a string for the first occurrence of any character except vowels.


See also REFind(), FindOneOf(), GetToken(), Left(), Mid(), Right()


ReleaseCOMObject()

Description: ReleaseCOMObject() releases a COM object from memory, freeing up resources. This function takes one parameter, the variable name that was used to create the object with the <cfobject> tag or CreateObject() function.

Syntax:

 ReleaseCOMObject(objectName) 

Example: The following example releases the object named FileMgr:

 #ReleaseCOMObject(FileMgr)# 

See also CreateObject()


RemoveChars()

Description: RemoveChars() returns a string with specified characters removed from it. This function is the exact opposite of the Mid() function. RemoveChars() takes three parameters: The first is the string from which to remove the characters; the second is the starting position of the characters to be removed; and the third is the number of characters to be removed. If no characters are found in the string being evaluated, the RemoveChars function returns 0.

Syntax:

 RemoveChars(String, StartPosition, Length) 

Example: The following example returns a field with characters 10 through 14 removed:

 #RemoveChars(product_code, 10, 5)# 

See also Left(), Mid(), Right()


RepeatString()

Description: RepeatString() returns a string made up of a specified string multiple times. RepeatString() takes two parameters: The first is the string to repeat, and the second is the number of occurrences.

Syntax:

 RepeatString(String, Count) 

Example: The following example creates a horizontal line made up of equals signs:

 #RepeatString("=", 80)# 

Replace()

Description: Replace() enables you to replace text within strings with alternative text. Replace() does a simple text comparison to locate the text to be replaced. It takes four parameters. The first parameter is the string to be processed; the second is the text to be replaced; the third is the text to replace it with. The fourth parameter is optional and specifies the scope of the replacements. Possible scope values are "ONE" to replace the first occurrence only, "ALL" to replace all occurrences, and "RECURSIVE" to replace all occurrences recursively.

Syntax:

 Replace(String, WhatString, WithString [, Scope]) 

Example: The following example replaces all occurrences of the text "US" in an address field with the text "USA":

 #Replace(address, "US", "USA", "ALL")# 

This next example replaces the area code "(313)" with the area code "(810)", and because no scope is specified, only the first occurrence of "(313)" is replaced:

 #Replace(phone, "(313)", "(810)")# 

TIP

The Replace() function is case sensitive, and there is no non-case-sensitive equivalent function. To perform a non-case-sensitive replacement, you first must convert both the search and target strings to either upper- or lowercase (using the UCase() or LCase() function).


See also REReplace(), REReplaceNoCase(), ReplaceList()


REReplace()

Description: REReplace() enables you to perform case-sensitive searches and replace text within strings with alternative text using regular expressions. It takes four parameters. The first parameter is the string to be processed; the second is the text to be replaced; the third is the text to replace it with. The fourth parameter is optional and specifies the scope of the replacements. Possible scope values are "ONE" to replace the first occurrence only, "ALL" to replace all occurrences, and "RECURSIVE" to replace all occurrences recursively.

Syntax:

 REReplace(String, WhatString, WithString [, Scope]) 

Example: The following example returns Cohn, by replacing the capital letter J with the capital letter C. The lowercase n was ignored because REReplace() is case-sensitive.

 #REReplace("John","J|N","C","ALL")# 

See also Replace(), REReplace(), ReplaceList()


REReplaceNoCase()

Description: REReplaceNoCase() enables you to perform non-case-sensitive searches and replace text within strings with alternative text using regular expressions. It takes four parameters. The first parameter is the string to be processed; the second is the text to be replaced; the third is the text to replace it with. The fourth parameter is optional and specifies the scope of the replacements. Possible scope values are "ONE" to replace the first occurrence only, "ALL" to replace all occurrences, and "RECURSIVE" to replace all occurrences recursively.

Syntax:

 REReplaceNoCase(String, WhatString, WithString [, Scope]) 

Example: The following example returns CohC, by replacing the capital letter J and n with the capital letter C.

 <cfoutput>#REReplaceNoCase("John","J|N","C","ALL")#</cfoutput> <P>REReplaceNoCase("John","J|N","C","ALL"): <cfoutput>#REReplaceNoCase("John","J|N","C","ALL")#</cfoutput> <P>REReplaceNoCase("John","[A-Z]","C","ALL") <cfoutput>#REReplaceNoCase("John","[A-Z]","C","ALL")#</cfoutput> 

See also Replace(), REReplace(), ReplaceList()


ReplaceList()

Description: ReplaceList() replaces all occurrences of elements in one string with corresponding elements in another. Both sets of elements must be specified as comma-delimited values, and an equal number of values must exist in each set. ReplaceList takes three parameters. The first is the string to be processed; the second is the set of values to be replaced; and the third is the set of values with which to replace them.

Syntax:

 ReplaceList(String, FindWhatList, ReplaceWithList) 

Example: The following example replaces all occurrences of state names with their appropriate abbreviations:

 #ReplaceList(address, "CA, IN, MI", "California, Indiana, Michigan")# 

TIP

The ReplaceList() function is case sensitive, and there is no non-case-sensitive equivalent function. To perform a non-case-sensitive replacement, you first must convert both the search and target strings to either upper- or lowercase (using the UCase() or LCase() function).


NOTE

Unlike other replacement functions, the ReplaceList() function takes no scope parameter. ReplaceList() replaces all occurrences of matching elements.


See also Replace()


Reverse()

Description: Reverse() reverses the characters in a string. Reverse() takes a single parameter: the string to be reversed.

Syntax:

 Reverse(String) 

Example: The following example reverses the contents of a user-supplied field:

 #Reverse(sequence_id)# 

Right()

Description: Right() returns the specified rightmost characters from the end of a string. Right() takes two parameters: the string from which to extract the characters and the number of characters to extract.

Syntax:

 Right(String, Count) 

Example: The following example returns the last seven characters of a phone number column:

 #Right(phone_number, 7)# 

TIP

Right() does not trim trailing spaces before extracting the specific characters. To ignore white space when using Right(), you should nest the RTrim() within Right(), as in #Right(RTrim(String), Count)#.


See also Find(), Left(), Mid(), RemoveChars()


RJustify()

Description: RJustify() right-aligns a string within a field of a specified length. It does this by padding spaces before the specified text. RJustify() takes two parameters: the string to process and the desired string length.

Syntax:

 RJustify(string, length) 

Example: The following example right-justifies the contents of a field named Zip so that it is right-aligned within a 10-character-wide field:

 #RJustify(Zip, 10)# 

See also CJustify(), LJustify(), LTrim(), RTrim(), Trim()


Round()

Description: Round() returns the integer (either greater or smaller) closest to the passed number. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Round(number) 

Example: The following example returns 2, the closest integer to 1.7:

 #Round("1.7")# 

See also Ceiling(), Fix(), Int()


RTrim()

Description: RTrim()TRims white space (spaces, tabs, and new-line characters) from the end of a string. RTrim() takes a single parameter: the string to be trimmed.

Syntax:

 RTrim(String) 

Example: The following example trims spaces from the end of a user-supplied field:

 #RTrim(first_name)# 

See also CJustify(), LJustify(), LTrim(), RJustify(), Trim(), StripCR()


Second()

Description: Second() returns a date/time object's second as a numeric value with possible values of 059. Second() takes a single parameter: the date/time object to be processed.

Syntax:

 Second(Date) 

Example: The following example returns the current minute's seconds:

 We are now #Second(Now())# seconds into the current minute 

TIP

Always enclose date/time values in quotes when passing them to the Second() function as strings. Without quotes, the value passed is interpreted as a numeral representation of a date/time object.


See also Day(), DayOfWeek(), DayOfYear(), Hour(), Minute(), Month(), Quarter(), Week(), Year()


SendGatewayMessage()

Description: SendGatewayMessage() is used to send messages through a ColdFusion event gateway's outGoingMessage() method. It takes two parameters: the Gateway Identifier (from the CF Administrator) and the data to send. The data that you send is dependent on the gateway you're working with. Typically, you'll send a structure that identifies a message and an address to which it is to be delivered.

The type of data returned is also dependent on the gateway. For example, if you're working with an SMS gateway in asynchronous mode, SendGatewayMesage() will return a logical value (true if the message could be queued for delivery). If the gateway is working synchronously, the function will wait for the message to be delivered and will get either a message ID value (if the delivery was successful) or and error message back.

Syntax:

SendGatewayMessage(gatewayID, data)

Example: The following example sends a message to an SMS synchronous gateway:

 <cfscript>   msgStruct = structNew();   msgStruct.command = "submit";   msgStruct.destAddress = "3134561234";   msgStruct.shorMessage = "Howdy Ben";   returnStatus = SendGatewayMessage("MC SMS 1", msgStruct);   WriteOutput(returnStatus); </cfscript> 

See also SetLocale()

Description: SetLocale() sets the name of the locale to be used by any subsequent calls to the LS functions. SetLocale() also returns the name of the currently active locale so that it can be saved if necessary.

Syntax:

 SetLocale(locale) 

Example: The following example sets the locale to British English and saves the current locale to a local variable:

 <cfset previous_locale = #SetLocale("English (UK)")#> 

See also GetLocale(),GetLocaleDisplayName()


SetProfileString()

Description: The SetProfileString() function sets the value of an entry in an initialization (*.ini) file.

Syntax:

 SetProfileString(iniPath, section, entry, value) 

Example: The following example sets the startup values to a passed value:

 #SetProfileString("app.ini", "Startup", "OnStartup", "#FORM.value#")# 

See also GetProfileString()


SetVariable()

Description: SetVariable() sets a specified variable to a passed value.

Syntax:

 SetVariable(Variable, Value) 

Example: The following example sets variable #cnt# to the value returned by the passed expression:

 #SetVariable("cnt", "A")# 

Sgn()

Description: Sgn() returns the sign: either 1, 0, or 1, depending on whether the passed number is negative, 0, or positive. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Sgn(number) 

Example: The following example returns 1, the sign of 4:

 #Sgn(4)# 

See also Abs()


Sin()

Description: Sin() returns the sine of a passed number. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Sin(number) 

Example: The following example returns -0.756802495308, the sine of 4:

 #Sin(4)# 

See also Asin(), Atn(), Cos(), Pi(), Tan()


SpanExcluding()

Description: SpanExcluding() exTRacts characters from the beginning of a string until a character that is part of a specified set is reached. SpanExcluding() takes two parameters: the string to process and a comma-delimited set of values to compare against.

Syntax:

 SpanExcluding(String, Set) 

Example: The following example extracts the first word of a sentence by specifying a space as the character to compare against:

 #SpanExcluding(sentence, " ")# 

TIP

The SpanExcluding() function is case sensitive, and there is no non-case-sensitive equivalent function. To perform a non-case-sensitive extraction, you first must convert both the search and target strings to either upper- or lowercase (using the UCase() or LCase() function).


See also SpanIncluding()


SpanIncluding()

Description: SpanIncluding() extracts characters from the beginning of a string only as long as they match characters in a specified set. SpanIncluding() takes two parameters: the string to process and a comma-delimited set of values to compare against.

Syntax:

 SpanIncluding(String, Set) 

Example: The following example extracts the house number from a street address by specifying a set of values that are digits only:

 #SpanIncluding(address, "1234567890")# 

TIP

The SpanIncluding()function is case sensitive, and there is no non-case-sensitive equivalent function. To perform a non-case-sensitive extraction, you first must convert both the search and target strings to either upper- or lowercase (using the UCase() or LCase()function).


See also SpanExcluding()


Sqr()

Description: Sqr() returns the square root of a passed number. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Sqr(number) 

Example: The following example returns 2, the square root of 4:

 #Sqr(4)# 

See also Abs()


StripCR()

Description: StripCR() removes all carriage return characters from a string. StripCR() takes a single parameter: the string to be processed.

Syntax:

 StripCR(String) 

Example: The following example removes carriage returns for a field to be displayed in a preformatted text block:

 <pre>#StripCR(comments)#</pre> 

TIP

The StripCR() function is particularly useful when displaying a string within HTML preformatted text tags (<pre> and </pre>) where carriage returns are not ignored.


See also CJustify(), LJustify(), LTrim(), RJustify(), RTrim(), Trim()


StructAppend()

Description: StructAppend() appends one structure to another. StructAppend() takes three parameters: the two structures (the second is appended to the first), and an overwrite flag specifying whether to overwrite existing items. StructAppend() always returns YES.

Syntax:

 StructAppend(struct1, struct2, flag) 

Example: The following example appends a structure overwriting any existing items:

 #StructAppend(keys, newkeys, TRUE)# 

See also Duplicate(), StructNew(), StructCopy()


StructClear()

Description: StructClear() deletes all data from a structure. StructClear() takes a single parameter: the structure to be cleared. StructClear() always returns YES if the operation is successful.

Syntax:

 StructClear(Structure) 

Example: The following example empties an existing structure:

 <cfset result = StructClear(Items)> 

NOTE

StructClear() does not delete the actual structure. Rather, it removes all of its contents. The structure itself remains and can be reused.


See also StructDelete(), StructIsEmpty()


StructCopy()

Description: StructCopy() returns a clone of the specified structure, with all the keys and values of the specified structure intact. The StructCopy() function takes a single parameter: the structure to be copied.

Syntax:

 StructCopy(structure) 

Example: The following example produces a clone of the structure People:

 StructCopy(People) 

NOTE

On the surface, StructCopy() appears similar to the Duplicate() function. The main difference is that when using the Duplicate() function to copy a structure, you are creating a completely new copy of the specified structure, with no reference to the original. StructCopy() assigns any nested structures, objects, or query values to the new structure by making reference to the original.


See also Duplicate(), StructClear()


StructCount()

Description: StructCount() returns the number of items in a specified structure. StructCount() takes a single parameter: the structure to be checked. ColdFusion will throw an error if the structure you are attempting to evaluate with StructCount() does not exist.

Syntax:

 StructCount(Structure) 

Example: The following example reports the number of elements in a structure:

 The items structure has #StructCount(items)# elements 

See also StructIsEmpty()


StructDelete()

Description: StructDelete() deletes an item from a structure. StructDelete() takes three parameters: the structure, the name of the key to be deleted, and an optional flag that specifies how to handle requests to delete a key that does not exist. StructDelete() returns YES if the operation is successful and NO if not. If an attempt is made to delete a key that does not exist, and the IndicateNotExisting flag is not set to trUE, the StructDelete() returns YES.

Syntax:

 StructDelete(Structure, Key [, IndicateNotExisting]) 

Example: The following example deletes the name key from a user structure:

 #StructDelete(user, name)# 

See also StructClear(), StructKeyExists(), StructIsEmpty()


StructFind()

Description: The StructFind() function searches through a structure to find the key that matches the specified search text. If a matching key is found, the value in that key is returned; if no match is found, an empty value is returned. This function takes two parameters: the first is the structure to be searched, and the second is the key for which to search.

Syntax:

 StructFind(Structure, Key) 

Example: The following example returns the user name stored in a user structure:

 Username is #StructFind(user, first_name)# 

See also StructFindKey(), StructFindValue()


StructFindKey()

Description: The StructFindKey() function searches recursively through a structure to find any keys that match the specified search text. If matching keys are found, they are returned in an array. This function takes three parameters: the first is the structure (or array) to be searched, the second is the key for which to search, the third is a scope flag specifying ONE to find the first match or ALL to find all matches.

Syntax:

 StructFindKey(Structure, Key, Scope) 

Example: The following example returns all keys that match a user specified string:

 <cfset results=StructFindKey(prods, FORM.search, "ALL")> 

See also StructFind(), StructFindValue()


StructFindValue()

Description: The StructFindValue() function searches recursively through a structure to find any items with values that match the specified search text. If matching items are found, they are returned in an array. This function takes three parameters: The first is the structure (or array) to be searched; the second is the key for which to search; and the third is a scope flag specifying ONE to find the first match or ALL to find all matches.

Syntax:

 StructFindValue(Structure, Key, Scope) 

Example: The following example returns all items with values that match a user-specified string:

 <cfset results=StructFindValue(prods, FORM.search, "ALL")> 

See also StructFind(), StructFindKey()


StructGet()

Description: StructGet() gets an array of structures from a specified path. StructGet() takes a single parameter: the path to be used.

Syntax:

 StructGet(Path) 

Example: The following example gets a structure from a specified path:

 <cfset struct=StructGet("catalog.product.widgets")> 

See also StructNew()


StructInsert()

Description: StructInsert() inserts an item into a structure. StructInsert() takes four parameters: the structure, the name of the key to be inserted, the value, and an optional flag that specifies whether a key can be overwritten. StructInsert() returns YES if the operation is successful and NO if not. Values can be overwritten unless AllowOverwrite is set to FALSE.

Syntax:

 StructInsert(Structure, Key, Value [, AllowOverwrite]) 

Example: The following example inserts a key named first_name into a user structure:

 #StructInsert(user, "first_name", "Ben")# 

See also StructDelete()


StructIsEmpty()

Description: StructIsEmpty() checks whether a structure has data. StructIsEmpty() takes a single parameter: the structure to be checked. StructIsEmpty() returns trUE if the array is empty and FALSE if not.

Syntax:

 StructIsEmpty(Structure) 

Example: The following example reports whether a structure is empty:

 <cfoutput>Strucure empty: #YesNoFormat(StructIsEmpty(Users))#</cfoutput> 

See also StructClear(), StructCount(), StructKeyExists()


StructKeyArray()

Description: The StructKeyArray() function returns the keys of a specified structure in an array. The StructKeyArray() function takes a single parameter: the structure to be evaluated.

Syntax:

 StructKeyArray(structure) 

Example: The following example returns, as an array, the keys of the specified structure:

 #StructKeyArray(family)# 

NOTE

The array the StructKeyArray() function returns is in no particular order. To sort the array, use the ArraySort() function. Also, remember that if the structure you are attempting to evaluate with the StructKeyArray() function does not exist, ColdFusion throws an error.


See also StructClear(), StructDelete(), StructFind(), StructUpdate()


StructKeyExists()

Description: StructKeyExists() checks whether a structure contains a specific key. StructKeyExists() takes two parameters: the structure to be checked and the key for which to look. StructKeyExists() returns TRUE if the key exists and FALSE if not.

Syntax:

 StructKeyExists(Structure, Key) 

Example: The following example checks whether a key named first_name exists:

 <cfif StructKeyExists(user, "first_name")> 

See also StructCount(), StructIsEmpty()


StructKeyList()

Description: StructKeyList() returns a list of keys in the specified ColdFusion structure. The StructKeyList() function takes two parameters. The first parameter is the structure to be evaluated. The second, optional parameter is the delimiter to separate each list item that is returned.

Syntax:

 StructKeyList(structure [,delimiter]) 

Example: The following example retrieves a list of keys, delimited by a comma, from the specified structure:

 #StructKeyList(MyStructure ,",")# 

See also StructKeyArray(), StructClear()


StructNew()

Description: StructNew() creates a new structure. StructNew() takes no parameters and returns the structure itself.

Syntax:

 StructNew() 

Example: The following example creates a simple structure:

 <cfset Orders = StructNew()> 

StructSort()

Description: The StructSort() function returns an array of structure keys sorted as needed. The StructSort() function takes four parameters. The first is the structure to sort. The second is an optional path to append to keys to reach the element to sort by. The third is the sort type, either NUMERIC, TEXT (the default), or TEXTNOCASE. The fourth is the sort order (ASC or DESC).

Syntax:

 StructSort(structure, path, sort, order) 

Example: The following example displays a list of keys sorted using defaults:

 <cfoutput>#ArrayToList(StructSort(products))# </cfoutput> 

StructUpdate()

Description: The StructUpdate() function updates the specified key in a given structure with a specified value. The function returns YES if the update is successful, and throws an exception if an error is encountered. The StructUpdate() function takes three parameters. The first is the structure you are attempting to update; the second is the key within the structure you are attempting to update; and the third is the value with which you want to update the specified key.

Syntax:

 StructUpdate(structure, key, value) 

Example: The following example updates the specified structure:

 #StructUpdate(stFamily, "wife", "Laura")# 

See also StructClear(), StructDelete(), StructFind()


Tan()

Description: Tan() returns the tangent of a passed number. This function takes only one numeric value as a parameter. You can pass real values, integer values, and ColdFusion fields to this function.

Syntax:

 Tan(number) 

Example: The following example returns 1.15782128235, the tangent of 4:

 #Tan(4)# 

See also Atn(), Asin(), Cos(), Sin(), Pi()


TimeFormat()

Description: TimeFormat() displays the time portion of a date/time object in a readable format. TimeFormat() takes two parameters. The first is the date/time object to be displayed, and the second is an optional mask value enabling you to control exactly how the data is formatted. If no mask is specified, the default mask of hh:mm tt is used. The complete set of date masks is listed in Table C.41.

Table C.41. TimeFormat() Mask Characters

MASK

DESCRIPTION

h

Hours in 12-hour clock format with no leading 0 for single-digit hours

hh

Hours in 12-hour clock format with a leading 0 for single-digit hours

H

Hours in 24-hour clock format with no leading 0 for single-digit hours

HH

Hours in 24-hour clock format with a leading 0 for single-digit hours

m

Minutes with no leading 0 for single-digit minutes

mm

Minutes with a leading 0 for single-digit minutes

s

Seconds with no leading 0 for single-digit seconds

ss

Seconds with a leading 0 for single-digit seconds

l

Milliseconds

t

Single-character meridian specifier, either A or P

tt

Two-character meridian specifier, either AM or PM


Syntax:

 TimeFormat(Date [, mask ]) 

Example: The following example displays the current time with the default formatting options:

 The time is: #TimeFormat(Now())# 

The next example displays the current time with seconds in 24-hour clock format:

 The time is: #TimeFormat(Now(), "HH:mm:ss")# 

NOTE

Unlike the DateFormat() function mask specifiers, the TimeFormat() function mask specifiers are case-sensitive on the hour mask.


NOTE

TimeFormat() supports U.S.-style times only. Use the LSTimeFormat() function for international time support.


See also DateFormat(), LSTimeFormat()


ToBase64()

Description: The ToBase64() function returns the Base64 representation of a specified string or binary object. Base64 format converts a string or an object to printable characters that can then be sent as text in e-mail or stored in a database. The ToBase64() function can take two parameters. The first is the string or binary value to be encoded. The second parameter, encoding, is optional and is used when working with binary data. It indicates how string data is to be encoded and can be set to US-ASCII, ISO-8859-1, UTF-8, or UTF-16.

Syntax:

 ToBase64(string or binary_value, encoding) 

Example: The following example converts a simple text string to Base64-encoded format:

 #ToBase64("Laura is a pretty girl")# 

NOTE

When converting a Base64-encoded string back to its original state, you first must convert this string to a binary object. After you've done that, you can use the ToString() function to convert the resulting binary object back into a string.


See also ToBinary(), IsBinary(), ToString()


ToBinary()

Description: The ToBinary() function either converts a Base64-encoded string to a binary representation. The ToBinary() function also takes a single parameter: the Base64-encoded string to be converted.

Syntax:

 ToBinary(encoded_string or binary_value) 

Example: The following example reads the contents of an image file into memory, converts the image file to a Base64-encoded string, and then converts the file from a Base64-encoded string back to a binary value:

 <cffile ACTION="READ"  file="FULL PATH OF THE IMAGE FILE"  variable="ImgFile"> <cfset EncodedImage = ToBase64(ImgFile)> <cfset BinaryImage = ToBinary(EncodedImage)> 

TIP

If you receive data in Base64-encoded format, the ToBinary function is useful for re-creating, out of the Base64-encoded string, the original binary object (.gif, .jpg, and so on).


NOTE

When converting a Base64-encoded string back to its original state, you first must convert this string to a binary object. After you've done that, you can use the ToString() function to convert the resulting binary object back into a string.


See also ToBase64(), IsBinary(), ToString()


ToScript()

Description: The ToScript() function creates JavaScript variables from ColdFusion variables. Strings, arrays, numbers, structures are queries and can all be converted from CFML to equivalent variables in JavaScript.

ToScript() requires that you provide the CFML variable and the name of JavaScript variable to be created. The third parameter, outputFormat, is optional. Setting it to true indicates that you want WDDX type output. If you set it to False, the output will be in ActionScript format. The fourth parameter, ASFormat, is optional and indicates whether or not you want Action Script shortcuts ([] for New Array and { } for New Object) in the script.

This difference only matters with complex data types, like queries. WDDX recordset objects are structures keyed on the column names. Each element in the structure contains an array of the row values for that element (column). ActionScript recordsets are arrays of structures. Here, rows are identified by the array index. Each array element contains a structure for each columnone structure element for each field.

Before you can use WDDX type output, be sure to include the ColdFusion JavasScript for WDDX like this:

 <script type="text/javascript" src="/books/2/448/1/html/2//CFIDE/scripts/wddx.js"> </script> 

Syntax:

 ToScript(CFVar, "JS var name"[, outputFormat,[ ASFormat]]) 

Example: The following example creates a WDDX structure from a query result then displays the value of the LastName field in the 10th row of the query result:

 <!--- get actor names ---> <cfquery name="getActors" datasource="ows">   SELECT NameLast, NameFirst   FROM Actors </cfquery> <html> <head> <!--- include CF WDDX.js so that WDDX objects will be available for use in the script. ---> <script type="text/javascript" src="/books/2/448/1/html/2/http://localhost:8500/CFIDE/scripts/wddx.js"> </script> <!--- Creates a JavaScript (WDDX format) variable form query results ---> <script language="JavaScript1.2">   <cfoutput>   var #toScript(getActors, "jsRecordSet", true)#;   </cfoutput>   //Display lastname from 10th row   alert( jsRecordSet["namelast"][10] );  </script> </head> <body>hello </body> </html> 

ToString()

Description: The ToString() function attempts to convert any value, including binary values, into a string. If the value specified can't be converted into a string, the ToString() function throws an exception error. The ToString() function takes two parameters. The first is the value to be converted to a string. The second is the name of the encoding scheme. This can be used when working with binary data and can be set to US-ASCII, ISO-8859-1, UTF-8 or UTF-16.

Syntax:

 ToString(any_value, encoding) 

Example: The following example converts the specified value into a string:

 #ToString(BinaryData, "ISO-8859-1")# 

trim()

Description: trim() trims white space (spaces, tabs, and new-line characters) from both the beginning and the end of a string. trim() takes a single parameter: the string to be trimmed.

Syntax:

 Trim(String) 

Example: The following example trims spaces from both the beginning and the end of a user- supplied field:

 #Trim(notes)# 

See also CJustify(), LJustify(), LTrim(), RJustify(), RTrim(), StripCR()


UCase()

Description: UCase() converts a string to uppercase. UCase() takes a single parameterthe string to be convertedand returns the converted string.

Syntax:

 UCase(String) 

Example: The following example converts the contents of a table column called States to uppercase:

 #UCase(State)# 

See also LCase()


URLDecode()

Description: The URLDecode() function decodes a specified URLEncoded string. The URLDecode() function takes a single parameter: the URLEncoded string to be decoded.

Syntax:

 URLDecode(urlEncodedString) 

Example: The following example decodes a URLEncoded string:

 #URLDecode(myEncodedString)# 

See also URLEncodedFormat()


URLEncodedFormat()

Description: URLEncodedFormat() encodes a string in a format that can safely be used within URLs. URLs can't contain spaces or any non-alphanumeric characters. The URLEncodedFormat() function replaces spaces with a plus sign; non-alphanumeric characters are replaced with equivalent hexadecimal escape sequences. URLEncodedFormat() takes a single parameterthe string to be encodedand returns the encoded string.

Syntax:

 URLEncodedValue(String) 

NOTE

ColdFusion automatically decodes all URL parameters that are passed to a template.


Example: The following example creates a URL with a name parameter that can safely include any characters:

 <a href="details.cfm?name=#URLEncodedFormat(name)#">Details</a> 

See also URLDecode()


Val()

Description: Val() converts the beginning of a string to a number. Val() takes a single parameter: the string to be processed. Conversion is possible only if the string begins with numeric characters. If conversion is impossible, 0 is returned.

Syntax:

 Val(String) 

Example: The following example extracts the hour portion from a time field:

 Hour: #Val(time)# 

TIP

Val() converts characters to numbers using a base of 10 only. To convert the string to numbers with a base other than 10, use the InputBaseN() function.


See also Asc(), Chr(), InputBaseN(), IsNumeric()


WriteOutput()

Description: The WriteOutput() function appends text to the page output stream, regardless of the setting specified in a given CFSETTING block. The WriteOutput() function takes a single parameter: the string to be output to the page.

Syntax:

 WriteOutput(string) 

Example: The following example writes the specified output to the page output stream:

 #WriteOutput("Users Processed: Sean, Misty, Parker, Laura, Peggy, Delane")# 

ValueList()

Description: ValueList() drives one query with the results of another. It takes a single parameterthe name of a query columnand return a list of all the values in that column. ValueList() returns a list of values that are separated by commas.

Syntax:

 ValueList(Column) 

Example: The following example passes the results from one query to a second query:

 SELECT * FROM Customers WHERE CustomerType IN (#ValueList(CustType.type)#) 

NOTE

The ValueList()function is typically used only when constructing dynamic SQL statements.


TIP

The values returned by ValueList() is in the standard ColdFusion list format and can therefore be manipulated by the list functions.


TIP

As a general rule, you always should try to combine both of the queries into a single SQL statement, unless you need to manipulate the values in the list. The time it takes to process one combined SQL statement is far less than the time it takes to process two simpler statements.


See also ValueList()


Week()

Description: Week() returns a date/time object's week in year as a numeric value with possible values of 152. Week() takes a single parameter: the date/time object to be processed.

Syntax:

 Week(Date) 

Example: The following example returns the current week in the year:

 This is week #Week(Now())# of year #Year(Now())# 

TIP

When specifying the year using the Week() function, be aware that ColdFusion will interpret the numeric values 029 as 21st-century years. The numeric values 3099 are interpreted as 20th-century years.


TIP

Always enclose date/time values in quotes when passing them to the Week() function as strings. Without quotes, the value passed is interpreted as a numeral representation of a date/time object.


See also Day(), DayOfWeek(), DayOfYear(), Hour(), Minute(), Month(), Quarter(), Second(), Year()


Wrap()

Description: Wrap() is used to wrap text to a specific line length. It requires two parametersthe text to wrap and the length to wrap it to. You can optionally use the third parameter to indicate whether or not you want any carriage-return or line-feed characters in the text to be removed (this defaults to False).

Syntax:

 Week(textValue, length[, Strip]) 

Example: The following example wraps a line to 25 characters:

 <cfset myText = "The quick brown fox jumped in the hen house ~CA  and ate some good lookin chicks."> <pre><cfoutput>#Wrap(myText, 25)#</cfoutput></pre> 

XMLChildPos()

Description: The XMLChildPos() function returns the position (within the children array) of a specified child, within an element.

Syntax:

 XMLChildPos(element, ChildName, StartingPos) 

Example: The following example converts the specified string to a format that is safe to use with XML:

 <cfscript> PhoneNbrPos = XmlChildPos( Employees.Employee, PhoneNbr, 1); if ( if PhoneNbrPos GT 0) {  // Employee has phone, delete it  ArrayDeleteAt( EmpPhone, PhoneNbrPos ); } else {  // Employee doesn't have phone, insert it  ArrayInsertAt( EmpPhone, PhoneNbrPos, Form.PhoneNbr ); } </cfscript> 

XMLElemNew()

Description: Returns the XML document object (first parameter) with a new child element created (specified in the third parameter). You can optionally include a namespace URI as the second parameter. It will generate an xmlns attribute in each element of this type that is created. (Namespaces are used to avoid ambiguities that arise when different XML documents being processed share elements with the same name.)

CF will automatically add the xmlns attribute to elements when you have included the namespace prefix in the childName parameter for those elements and the namespace parameter for (corresponding to that prefix) somewhere else in the xml.

Syntax:

 XMLElemNew(XMLDocObj[, nameSpace], childName) 

Example: The following example adds the element named "order" to the Orders XML document object:

 <cfscript> myOrders.Order.XmlChildren[1] = XmlElemNew(myOrders,"OrderLine"); </cfscript> 

XMLFormat()

Description: The XMLFormat() function formats a specified string so that it is safe to use with XML. The XMLFormat() function takes a single parameter: the string to be formatted. The function escapes any special XML characters so you can put these characters in strings that you pass as XML. The characters that are escaped by the XMLFormat() function include > (greater than sign), < (less than sign), ' (single quotation mark), " (double quotation mark), and & (ampersand).

Syntax:

 XMLFormat("Text to be formatted") 

Example: The following example converts the specified string to a format that is safe to use with XML:

 <xmp> <?xml version = "1.0"?>  <cfoutput> <BizRules>  <rule body="#xmlFormat('Value >= 1')#" action="#xmlFormat('Set value to "Bob"')#">  <rule body="#xmlFormat('Value < 1')#" action='#xmlFormat("Set value to 'Jane'")#'> </BizRules> </cfoutput> </xmp> 

XMLGetNodeType()

Description: The XMLGetNodeType() function takes one parametera node from an XML object (or the object itself)and returns one of several constant values that indicating the type of node it is. The possible return values are:

  • ATTRIBUTE_NODE

  • CDATA_SECTION_NODE

  • COMMENT_NODE

  • DOCUMENT_FRAGMENT_NODE

  • DOCUMENT_NODE

  • DOCUMENT_TYPE_NODE

  • ELEMENT_NODE

  • ENTITY_NODE

  • ENTITY_REFERENCE_NODE

  • NOTATION_NODE

  • PROCESSING_INSTRUCTION_NODE

  • TEXT_NODE

Syntax:

 XMLGetNodeType(nodeObject) 

Example: The following example creates an XML object. It then displays the types of nodes represented by the document itself and other nodes:

 <cfxml variable="xmlPeople"> <?xml version="1.0" encoding="UTF-8"?> <people>   <person >     <name type="first">joe</name>     <name type="last">blow</name>     <phone type="home">323-232-1111</phone>     <children>       <child firstName="Frank" />       <child firstName="Betty" />     </children>   </person> </people> </cfxml> <cfoutput> <p>root ojbect: #XMLGetNodeType(xmlPeople)#</p> <p>person node: #XMLGetNodeType(xmlPeople.people.person)#</p> <cfset myPersonArray = xmlPeople.people.person.XMLNodes> <cfloop from="1" to="#arraylen(myPersonArray)#" index="ii">   <p>#myPersonArray[ii].XMLName#: #XMLGetNodeType(myPersonArray[ii])#</p> </cfloop> </cfoutput> 

XMLNew()

Description: The XMLNew() function returns a new, empty XML document object. It takes one parameter, which indicates whether case sensitivity is to be used. This should be set to either YES or NO.

Syntax:

 XMLNew(CaseSensitive) 

Example: The following example converts the specified string to a format that is safe to use with XML:

 <!--- Create new XML document object ---> <cfset NewDoc = XMLNew("No")> <!--- Display the new object ---> <cfdump var="#NewDoc#"> 

XMLParse()

Description: The XMLParse() function converts a string of XML into an XML document object. It takes up to three parameters: the string value, a value of YES or NO, indicating case sensitivity and a reference to a DTD to validate the XML with.

The validator can be presented in several forms:

  • The URL of a DTD or XML Schema file

  • The name of a DTD or XML Schema file

  • A string containing the DTD or Schema

Use an empty string value for validator if the XML file you're parsing contains a DTD or Schema identifier.Syntax:

 XMLParse(string[, CaseSensitive], validator]]) 

Example: The following example converts the specified string to a format that is safe to use with XML:

 <!--- Read XML document into a variable. ---> <cffile action="READ"  file="c:\neo\wwwroot\ows\c\Orders.xml"   variable="myXMLfile"> <!--- Create new CF XML document object ---> <cfset x=XMLParse(myXMLfile, "no")> <!--- Display new CF XML document object ---> <cfdump var="#x#"> 

NOTE

If your XML document is case sensitve, you can't use dot notation to indicate elements or attirbute names.


XMLSearch()

Description: The XMLSearch() function uses an XPath expression to search an XML document object. It returns an array of matching object nodes that match the search criteria.

Syntax:

 XMLSearch(XMLDocObj, XPath_exp) 

Example: The following example reads an XML file into a string and converts it to an XML document object. It then searches for the "order" elements in the "orders" node. It then outputs the name for each order that it found:

 <cffile action="READ" file="c:\neo\wwwroot\ows\c\Orders.xml" variable="myXMLfile"> <cfscript> myXMLdoc = XMLParse(myXMLfile); someElements = XMLSearch(myXMLdoc, "/orders/order"); for (i = 1; i LTE ArrayLen(someElements); i = i + 1) {  WriteOutput( "Child " & i & " = " & someElements[i].XMLName & "<br />"); } </cfscript> 

XMLTransform()

Description: XMLTransform() transforms an XML document object to a string, formatted via a specified XSLT (an XML transformation style sheet). It takes up to three parameters: the XML string, the XML style sheet string and a structure containing name/value pairs to be used by the XSLTdoc.

Syntax:

 XMLTransform(XMLDoc, XSLTdoc[, parameters]) 

Example: The following example reads an XML file into a string and reads an XSLT transformation template into another variable. These are used by XMLTransform() to generate nicely formatted HTML output:

 <!--- Read XML file into xmlsource variable ---> <cffile action="READ"   file="c:\neo\wwwroot\ows\c\Orders.xml" variable="xmlsource"> <!--- Read XSLT template into xslsource variable ---> <cffile action="READ"   file="c:\neo\wwwroot\ows\c\Orders.xsl" variable="xslsource"> <!--- Transform xmlsource into nicely formatted HTML ---> <cfset Result = XmlTransform(xmlsource, xslsource)> <!--- Display output ---> <cfcontent TYPE="text/html"> <cfoutput>#Result#</cfoutput> 

XMLValidate()

Description: You supply XMLValidate() with an XML Schema or a DTD and it will validate an XML object or XML text. It takes two parameters, xmlDoc and optionally, validator. The xmlDoc can be:

  • A string containing an XML document

  • The name of an XML file

  • A URL (using http, https, ftp or file protocols)

  • An XML document object

The validator parameter can be:

  • A string containing a DTD or Schema

  • The name of a DTD or Schema file

  • The URL of a DTD or Schema file (can use http, https, ftp or file protocols)

It returns a structure containing the elements described in Table C.42

Table C.42. XMLValidate() Return Structure

ELEMENT

DESCRIPTION

errors

An array containing error messages from the validator.

fatalErrors

An array containing fatal error messages from the validator.

status

True if the XML is valid. False if it isn't.

warning

An array containing warning messages from the validator.


Note that if you omit the validator parameter and the XML does not identify a DTD or Schema (with a <!DOCTYPE> tag), XMLValidate() will return an error message in the errors element of the return value structure. If the XML includes a <!DOCTYPE> tag that specifies a DTD or Schema and you provide a validator parameter too, the validator parameter will be used to validate the XML, ignoring the <!DOCTYPE> tag.

Syntax:

 XMLValidate(XMLDcoument[, validator]) 

Example: The example below uses a local Schema file, person.xsd, and validates a local xml file with it. The .xsd file is presented, then the .xml and then the code that employs XMLValidate().

 <?xml version="1.0" encoding="UTF-8"?> <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">   <xs:element name="person">   </xs:element>   <xs:element name="people">     <xs:complexType>       <xs:sequence>         <xs:element ref="person" maxOccurs="unbounded" />       </xs:sequence>     </xs:complexType>   </xs:element> </xs:schema> 

Here's the .xml file:

 <?xml version="1.0" encoding="UTF-8"?> <people>   <person>This is a person</person> </people> 

And here's the code to do the validation:

 <cfset validStruct=XMLValidate( ~CA "C:\blackstone\wwwroot\ows\c\person.xml",  ~CA "http://localhost:8500/ows/c/person.xsd")> Was persons.xml validated successfuly by pseron.xsd? <cfoutput>#validStruct.status#</cfoutput> <p>Dump of validStruct returned by XMLValidate()<br> <cfdump var="#validStruct#"></p> 

See also IsXMLDoc()


Year()

Description: Year() returns a date/time object's year as a numeric value with possible values of 1009999. Year() takes a single parameter: the date/time object to be processed.

Syntax:

 Year(Date) 

Example: The following example returns the current year value:

 It is year #Year(Now())# 

See also Day(), DayOfWeek(), DayOfYear(), Hour(), Minute(), Month(), Quarter(), Second(), Week()


YesNoFormat()

Description: YesNoFormat() converts TRUE and FALSE values to Yes and No. YesNoFormat() takes a single parameterthe number, string, or expression to evaluate. When evaluating numbers, YesNoFormat() treats 0 as NO and any nonzero value as YES.

Syntax:

 YesNoFormat(Value) 

Example: The following example converts a table Boolean value to a Yes or No string:

 Member: <cfoutput>#YesNoFormat(member)#</cfoutput> 

See also IsBoolean()




Macromedia Coldfusion MX 7 Web Application Construction Kit
Macromedia Coldfusion MX 7 Web Application Construction Kit
ISBN: 321223675
EAN: N/A
Year: 2006
Pages: 282

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net