- CFML Reference User Guide
- ColdFusion functions
- ColdFusion functions by category
- Functions a-b
- Abs
- ACos
- AddSOAPRequestHeader
- AddSOAPResponseHeader
- AjaxLink
- AjaxOnLoad
- ApplicationStop
- ArrayAppend
- ArrayAvg
- ArrayClear
- ArrayContains
- ArrayContainsNoCase
- ArrayDelete
- ArrayDeleteAt
- ArrayDeleteNoCase
- ArrayEach
- ArrayFilter
- ArrayFind
- ArrayFindAll
- ArrayFindAllNoCase
- ArrayFindNoCase
- ArrayInsertAt
- ArrayIsDefined
- ArrayIsEmpty
- ArrayLen
- ArrayMap
- ArrayMax
- ArrayMin
- ArrayNew
- ArrayPrepend
- ArrayReduce
- ArrayResize
- ArraySet
- ArraySetMetadata
- ArraySlice
- ArraySort
- ArraySum
- ArraySwap
- ArrayToList
- Asc
- ASin
- Atn
- AuthenticatedContext
- AuthenticatedUser
- BinaryDecode
- BinaryEncode
- BitAnd
- BitMaskClear
- BitMaskRead
- BitMaskSet
- BitNot
- BitOr
- BitSHLN
- BitSHRN
- BitXor
- BooleanFormat
- Abs
- Functions-c-d
- CacheGet
- CacheGetAllIds
- CacheGetMetadata
- CacheGetProperties
- CacheGetSession
- CacheIdExists
- CachePut
- CacheRegionExists
- CacheRegionNew
- CacheRegionRemove
- CacheRemove
- CacheRemoveAll
- CacheSetProperties
- CallStackDump
- CallStackGet
- CanDeSerialize
- Canonicalize
- CanSerialize
- Ceiling
- CharsetDecode
- CharsetEncode
- Chr
- CJustify
- Compare
- CompareNoCase
- Cos
- CreateDate
- CreateDateTime
- CreateObject
- CreateObject: .NET object
- CreateObject: COM object
- CreateObject: component object
- CreateObject: CORBA object
- CreateObject: Java or EJB object
- CreateObject: web service object
- CreateODBCDate
- CreateODBCDateTime
- CreateODBCTime
- CreateSignedJWT
- CreateEncryptedJWT
- CreateTime
- CreateTimeSpan
- CreateUUID
- CSRFGenerateToken
- CSRFVerifyToken
- CSVRead
- CSVWrite
- CSVProcess
- DateAdd
- DateCompare
- DateConvert
- DateDiff
- DateFormat
- DatePart
- DateTimeFormat
- Day
- DayOfWeek
- DayOfWeekAsString
- DayOfYear
- DaysInMonth
- DaysInYear
- DE
- DecimalFormat
- DecodeForHTML
- DecodeFromURL
- DecrementValue
- Decrypt
- DecryptBinary
- DeleteClientVariable
- Deserialize
- DeserializeJSON
- DeserializeXML
- DirectoryCopy
- DirectoryCreate
- DirectoryDelete
- DirectoryExists
- DirectoryList
- DirectoryRename
- DollarFormat
- DotNetToCFType
- Duplicate
- Functions-e-g
- EncodeForCSS
- EncodeForDN
- EncodeForHTML
- EncodeForHTMLAttribute
- EncodeForJavaScript
- EncodeForLDAP
- EncodeForURL
- EncodeForXML
- EncodeForXMLAttribute
- EncodeForXpath
- Encrypt
- EncryptBinary
- EntityDelete
- EntityLoad
- EntityLoadByExample
- EntityLoadByPK
- EntityMerge
- EntityNew
- EntityReload
- EntitySave
- EntityToQuery
- Evaluate
- Exp
- ExpandPath
- FileClose
- FileCopy
- FileDelete
- FileExists
- FileGetMimeType
- FileIsEOF
- FileMove
- FileOpen
- FileRead
- FileReadBinary
- FileReadLine
- FileSeek
- FileSetAccessMode
- FileSetAttribute
- FileSetLastModified
- FileSkipBytes
- FileUpload
- FileUploadAll
- FileWrite
- FileWriteLine
- Find
- FindNoCase
- FindOneOf
- FirstDayOfMonth
- Fix
- Floor
- FormatBaseN
- GeneratePBKDFKey
- GenerateSecretKey
- GetApplicationMetadata
- GetAuthUser
- GetBaseTagData
- GetBaseTagList
- GetBaseTemplatePath
- GetClientVariablesList
- GetComponentMetaData
- GetContextRoot
- GetCPUUsage
- GetCurrentTemplatePath
- GetCSPNonce
- GetDirectoryFromPath
- GetEncoding
- GetException
- GetFileFromPath
- GetFileInfo
- GetFreeSpace
- GetFunctionCalledName
- GetFunctionList
- GetGatewayHelper
- GetHttpRequestData
- GetHttpTimeString
- GetK2ServerDocCount
- GetK2ServerDocCountLimit
- GetLocale
- GetLocaleDisplayName
- GetLocalHostIP
- GetMetaData
- GetMetricData
- GetPageContext
- GetPropertyString
- GetPropertyFile
- GetPrinterInfo
- GetPrinterList
- GetProfileSections
- GetProfileString
- GetReadableImageFormats
- GetSafeHTML
- GetSAMLAuthRequest
- GetSAMLLogoutRequest
- Generate3DesKey
- GenerateSAMLSPMetadata
- GetSOAPRequest
- GetSOAPRequestHeader
- GetSOAPResponse
- GetSOAPResponseHeader
- GetSystemFreeMemory
- GetSystemTotalMemory
- GetTempDirectory
- GetTempFile
- GetTemplatePath
- GetTickCount
- GetTimeZoneInfo
- GetToken
- GetTotalSpace
- GetUserRoles
- GetVFSMetaData
- GetWriteableImageFormats
- Functions-h-im
- Hash
- HMac
- Hour
- HQLMethods
- HTMLCodeFormat
- HTMLEditFormat
- IIf
- ImageAddBorder
- ImageBlur
- ImageClearRect
- ImageCopy
- ImageCreateCaptcha
- ImageCrop
- ImageDrawArc
- ImageDrawBeveledRect
- ImageDrawCubicCurve
- ImageDrawLine
- ImageDrawLines
- ImageDrawOval
- ImageDrawPoint
- ImageDrawQuadraticCurve
- ImageDrawRect
- ImageDrawRoundRect
- ImageDrawText
- ImageFlip
- ImageGetBlob
- ImageGetBufferedImage
- ImageGetEXIFMetadata
- ImageGetEXIFTag
- ImageGetHeight
- ImageGetIPTCMetadata
- ImageGetIPTCTag
- ImageGetMetadata
- ImageGetWidth
- ImageGrayscale
- ImageInfo
- ImageMakeColorTransparent
- ImageMakeTranslucent
- ImageNegative
- ImageNew
- ImageOverlay
- ImagePaste
- ImageRead
- ImageReadBase64
- ImageResize
- ImageRotate
- ImageRotateDrawingAxis
- ImageScaleToFit
- ImageSetAntialiasing
- ImageSetBackgroundColor
- ImageSetDrawingColor
- ImageSetDrawingStroke
- ImageSetDrawingTransparency
- ImageSharpen
- ImageShear
- ImageShearDrawingAxis
- ImageTranslate
- ImageTranslateDrawingAxis
- ImageWrite
- ImageWriteBase64
- ImageXORDrawingMode
- Functions-in-k
- IncrementValue
- InputBaseN
- Insert
- Int
- InterruptThread
- InvalidateOauthAccesstoken
- Invoke
- InitSAMLAuthRequest
- InitSAMLLogoutRequest
- InvokeCFClientFunction
- IsArray
- IsAuthenticated
- IsAuthorized
- IsBinary
- IsBoolean
- IsClosure
- IsCustomFunction
- IsDate
- IsDateObject
- IsDDX
- IsDebugMode
- IsDefined
- IsImage
- IsImageFile
- IsInstanceOf
- IsIPv6
- IsJSON
- IsK2ServerABroker
- IsK2ServerDocCountExceeded
- IsK2ServerOnline
- IsLeapYear
- IsLocalHost
- IsNull
- IsNumeric
- IsNumericDate
- IsObject
- isOnline
- IsPDFArchive
- IsPDFFile
- IsPDFObject
- IsProtected
- IsQuery
- isSamlLogoutResponse
- isSafeHTML
- IsSimpleValue
- IsSOAPRequest
- IsSpreadsheetFile
- IsSpreadsheetObject
- IsStruct
- isThreadInterrupted
- IsUserInAnyRole
- IsUserInRole
- IsUserLoggedIn
- IsValid
- IsValidOauthAccesstoken
- IsWDDX
- IsXML
- IsXmlAttribute
- IsXmlDoc
- IsXmlElem
- IsXmlNode
- IsXmlRoot
- JavaCast
- JSStringFormat
- Functions-l
- LCase
- Left
- Len
- ListAppend
- ListChangeDelims
- ListContains
- ListContainsNoCase
- ListDeleteAt
- ListEach
- ListFilter
- ListFind
- ListFindNoCase
- ListFirst
- ListGetAt
- ListGetDuplicates
- ListInsertAt
- ListLast
- ListLen
- ListMap
- ListPrepend
- ListQualify
- ListReduce
- ListRemoveDuplicates
- ListRest
- ListSetAt
- ListSort
- ListToArray
- ListValueCount
- ListValueCountNoCase
- LJustify
- Location
- Log
- Log10
- LSCurrencyFormat
- LSDateFormat
- LSDateTimeFormat
- LSEuroCurrencyFormat
- LSIsCurrency
- LSIsDate
- LSIsNumeric
- LSNumberFormat
- LSParseCurrency
- LSParseDateTime
- LSParseEuroCurrency
- LSParseNumber
- LSTimeFormat
- LTrim
- Functions-m-r
- Max
- Mid
- Min
- Minute
- Month
- MonthAsString
- Now
- NumberFormat
- ObjectEquals
- ObjectLoad
- ObjectSave
- OnWSAuthenticate
- ORMClearSession
- ORMCloseAllSessions
- ORMCloseSession
- ORMEvictCollection
- ORMEvictEntity
- ORMEvictQueries
- ORMExecuteQuery
- ORMFlush
- ORMFlushall
- ORMGetSession
- ORMGetSessionFactory
- ORMIndex
- ORMIndexPurge
- ORMReload
- ORMSearch
- ORMSearchOffline
- ParagraphFormat
- ParameterExists
- ParseDateTime
- Pi
- PrecisionEvaluate
- ProcessSAMLResponse
- ProcessSAMLLogoutRequest
- Quarter
- PreserveSingleQuotes
- QueryAddColumn
- QueryAddRow
- QueryConvertForGrid
- QueryExecute
- QueryFilter
- QueryGetResult
- QueryGetRow
- QueryKeyExists
- QueryMap
- QueryNew
- QueryReduce
- QuerySetCell
- QuotedValueList
- QueryEach
- Rand
- Randomize
- RandRange
- ReEscape
- REFind
- REFindNoCase
- ReleaseComObject
- REMatch
- REMatchNoCase
- RemoveCachedQuery
- RemoveChars
- RepeatString
- Replace
- ReplaceList
- ReplaceNoCase
- REReplace
- REReplaceNoCase
- RestDeleteApplication
- RestSetResponse
- RestInitApplication
- Reverse
- Right
- RJustify
- Round
- RTrim
- Functions-s
- Second
- SendGatewayMessage
- SendSAMLLogoutResponse
- Serialize
- SerializeJSON
- SerializeXML
- SessionInvalidate
- SessionRotate
- SessionGetMetaData
- SessionInvalidate
- SessionRotate
- SetDay
- SetEncoding
- SetHour
- SetLocale
- SetMonth
- SetProfileString
- SetPropertyString
- SetVariable
- SetYear
- Sgn
- Sin
- Sleep
- SpanExcluding
- SpanIncluding
- SpreadsheetAddAutoFilter
- SpreadsheetAddColumn
- SpreadsheetAddFreezePane
- SpreadsheetAddImage
- SpreadsheetAddInfo
- SpreadsheetAddPageBreaks
- SpreadsheetAddRow
- SpreadsheetAddRows
- SpreadsheetAddSplitPane
- SpreadsheetCreateSheet
- SpreadsheetDeleteColumn
- SpreadsheetDeleteColumns
- SpreadsheetDeleteRow
- SpreadsheetDeleteRows
- SpreadsheetFormatCell
- SpreadsheetFormatColumn
- SpreadsheetFormatCellRange
- SpreadsheetFormatColumn
- SpreadsheetFormatColumns
- SpreadsheetFormatRow
- SpreadsheetFormatRows
- SpreadsheetGetCellComment
- SpreadsheetGetCellFormula
- SpreadsheetGetCellValue
- SpreadsheetGetColumnCount
- SpreadsheetInfo
- SpreadsheetMergeCells
- SpreadsheetNew
- SpreadsheetRead
- SpreadsheetReadBinary
- SpreadsheetRemoveSheet
- SpreadsheetSetActiveSheet
- SpreadsheetSetActiveSheetNumber
- SpreadsheetSetCellComment
- SpreadsheetSetCellFormula
- SpreadsheetSetCellValue
- SpreadsheetSetColumnWidth
- SpreadsheetSetFooter
- SpreadsheetSetHeader
- SpreadsheetSetRowHeight
- SpreadsheetShiftColumns
- SpreadsheetShiftRows
- SpreadsheetWrite
- StreamingSpreadsheetNew
- StreamingSpreadsheetCleanup
- StreamingSpreadsheetRead
- StreamingSpreadsheetProcess
- SpreadsheetSetFooterImage
- SpreadsheetSetHeaderImage
- SpreadsheetSetFittoPage
- SpreadsheetUngroupColumns
- SpreadsheetGroupColumns
- SpreadsheetUngroupRows
- SpreadsheetGroupRows
- SpreadsheetRemoveColumnBreak
- SpreadsheetSetColumnBreak
- SpreadsheetRemoveRowBreak
- SpreadsheetSetRowBreak
- SpreadsheetRemovePrintGridlines
- SpreadsheetAddPrintGridlines
- SpreadsheetGetColumnWidth
- SpreadsheetSetColumnHidden
- SpreadsheetSetRowHidden
- SpreadsheetisColumnHidden
- SpreadsheetisRowHidden
- SpreadsheetisStreamingXmlFormat
- SpreadsheetisXmlFormat
- SpreadsheetisBinaryFormat
- SpreadsheetRenameSheet
- SpreadsheetRemoveSheetNumber
- SpreadsheetGetLastRowNumber
- SpreadsheetGetPrintOrientation
- Sqr
- StripCR
- StructAppend
- StructClear
- StructCopy
- StructCount
- StructDelete
- StructEach
- StructFilter
- StructFind
- StructFindKey
- StructFindValue
- StructGet
- StructGetMetadata
- StructInsert
- StructIsEmpty
- StructKeyArray
- StructKeyExists
- StructKeyList
- StructMap
- StructNew
- StructReduce
- StructSetMetadata
- StructSort
- StructToSorted
- StructUpdate
- StructValueArray
- StoreSetMetadata
- StoreGetACL
- StoreGetMetadata
- StoreAddACL
- StoreSetACL
- Functions-t-z
- Tan
- ThreadJoin
- ThreadTerminate
- Throw
- TimeFormat
- ToBase64
- ToBinary
- ToScript
- ToString
- Trace
- Transactionandconcurrency
- TransactionCommit
- TransactionRollback
- TransactionSetSavePoint
- Trim
- UCase
- URLDecode
- URLEncodedFormat
- URLSessionFormat
- Val
- ValueList
- VerifyClient
- Week
- Wrap
- WriteDump
- WriteLog
- WriteOutput
- WSGetAllChannels
- WSGetSubscribers
- WSPublish
- WSSendMessage
- XmlChildPos
- XmlElemNew
- XmlFormat
- XmlGetNodeType
- XmlNew
- XmlParse
- XmlSearch
- XmlTransform
- XmlValidate
- Year
- YesNoFormat
- ColdFusion tags
- ColdFusion tag summary
- ColdFusion tags by category
- Application framework tags
- Communications tags
- Database manipulation tags
- Data output tags
- Debugging tags
- Exception handling tags
- Extensibility tags
- File management tags
- Flow-control tags
- Forms tags
- Internet Protocol tags
- Page processing tags
- Security tags
- Variable manipulation tags
- Other tags
- Tags a-b
- Tags c
- cfcache
- cfcalendar
- cfcase
- cfcatch
- cfchart
- cfchart tag in ColdFusion
- Get started with cfchart
- Customize a chart using cfchart
- Advanced cfchart customization options
- Create an area chart in ColdFusion
- Create line charts in ColdFusion
- Create bar charts in ColdFusion
- Create floating bar charts in ColdFusion
- Create histograms in ColdFusion
- Create pie charts in ColdFusion
- Create funnel charts in ColdFusion
- Create pyramid charts in ColdFusion
- Create curve charts in ColdFusion
- Create boxplots in ColdFusion
- Create donut charts in ColdFusion
- Create bubble charts in ColdFusion
- Create scatterplots in ColdFusion
- Create radar charts in ColdFusion
- Other chart types in ColdFusion (Cone, Cylinder, Piano, and Bullet)
- Advanced customization options in cfchart
- cfchartdata
- cfchartseries
- cfchartset
- cfclient
- cfclientsettings
- cfcol
- cfcollection
- cfcomponent
- cfcontent
- cfcontinue
- cfcookie
- Tags f
- cffeed
- cffile
- cffile action = "append"
- cffile action = "copy"
- cffile action = "delete"
- cffile action = "move"
- cffile action = "read"
- cffile action = "readBinary"
- cffile action = "rename"
- cffile action = "upload"
- cffile action = "uploadAll"
- cffile action = "write"
- cffileupload
- cffinally
- cfflush
- cfform
- cfformgroup
- cfformitem
- cfftp
- cfftp: Connection: file and directory operations
- cfftp: Opening and closing FTP server connections
- cfftp : Opening and closing secure FTP server connections
- cfftp action = "listDir"
- cffunction
- Tags g-h
- Tags i
- Tags j-l
- cfjava
- cflayout
- cflayoutarea
- cfldap
- cflocation
- cflock
- cflog
- cflogin
- cfloginuser
- cflogout
- cfloop
- cfloop : conditional loop
- cfloop : index loop
- cfloop : looping over a COM collection or structure
- cfloop : looping over a date or time range
- cfloop : looping over a list, a file, or an array
- cfloop : looping over a query
- Tags m-o
- cfmail
- cfmailparam
- cfmailpart
- cfmap
- cfmapitem
- cfmediaplayer
- cfmenu
- cfmenuitem
- cfmessagebox
- cfmodule
- cfNTauthenticate
- cfoauth
- cfobject
- cfobject: .NET object
- cfobject: COM object
- cfobject: component object
- cfobject: CORBA object
- cfobject: Java or EJB object
- cfobject: web service object
- cfobjectcache
- cfoutput
- Tags p-q
- Tags r-s
- Tags t
- Tags u-z
- CFML Reference
- Reserved words and variables
- Ajax JavaScript functions
- Ajax JavaScript functions
- Function summary Ajax
- ColdFusion.Ajax.submitForm
- ColdFusion.Autosuggest.getAutosuggestObject
- ColdFusion.Layout.enableSourceBind
- ColdFusion.MessageBox.getMessageBoxObject
- ColdFusion.ProgressBar.getProgressBarObject
- ColdFusion.MessageBox.isMessageBoxDefined
- JavaScriptFunctionsinColdFusion9Update1
- ColdFusion ActionScript functions
- ColdFusion mobile functions
- Application.cfc reference
- Script functions implemented as CFCs
- ColdFusion Flash Form style reference
- Styles valid for all controls
- Styles for cfform
- Styles for cfformgroup with horizontal or vertical type attributes
- Styles for box-style cfformgroup elements
- Styles for cfformgroup with accordion type attribute
- Styles for cfformgroup with tabnavigator type attribute
- Styles for cfformitem with hrule or vrule type attributes
- Styles for cfinput with radio, checkbox, button, image, or submit type attributes
- Styles for cftextarea tag and cfinput with text, password, or hidden type attributes
- Styles for cfselect with size attribute value of 1
- Styles for cfselect with size attribute value greater than 1
- Styles for cfcalendar tag and cfinput with dateField type attribute
- Styles for the cfgrid tag
- Styles for the cftree tag
- ColdFusion Flash Form Style Reference
- ColdFusion event gateway reference
- ColdFusion Event Gateway reference
- addEvent
- CFEvent
- CFEventclass
- Constructor
- Gateway development interfaces and classes
- getStatus
- setCFCPath
- setCFCMethod
- getOriginatorID
- getLogger
- getBuddyList
- getBuddyInfo
- IM gateway message sending commands
- IM Gateway GatewayHelper class methods
- onIncomingMessage
- onIMServerMessage
- onBuddyStatus
- onAddBuddyResponse
- onAddBuddyRequest
- IM Gateway CFC incoming message methods
- IM gateway methods and commands
- CFML CFEvent structure
- warn
- info
- setOriginatorID
- data command
- submit Multi command
- submit command
- setGatewayType
- setGatewayID
- setData
- setCFCListeners
- outgoingMessage
- getStatusTimeStamp
- numberOfMessagesReceived
- numberOfMessagesSent
- removeBuddy
- removeDeny
- removePermit
- setNickName
- setPermitMode
- setStatus
- SMS Gateway CFEvent structure and commands
- SMS Gateway incoming message CFEvent structure
- getStatusAsString
- getProtocolName
- getPermitMode
- getPermitList
- getNickName
- getName
- getDenyList
- getCustomAwayMessage
- getQueueSize
- getMaxQueueSize
- getHelper
- getGatewayType
- getGatewayServices
- getGatewayID_1
- getGatewayID
- getData
- getCFCTimeout
- setCFCTimeout
- getCFCPath
- getCFCMethod
- GatewayServices class
- Gateway interface
- GatewayHelper interface
- addPermit
- addDeny
- addBuddy
- error
- debug
- Logger class
- stop
- start
- CFML event gateway SendGatewayMessage data parameter
- restart
- fatal
- SMS gateway message sending commands
- ColdFusion C++ CFX Reference
- ColdFusion Java CFX reference
- WDDX JavaScript Objects
- Cloud services
- ColdFusion and GCP Storage
- ColdFusion and GCP Firestore
- ColdFusion and GCP PubSub
- ColdFusion and Amazon S3
- ColdFusion and DynamoDB
- ColdFusion and Amazon SQS
- ColdFusion and Amazon SNS
- ColdFusion and MongoDB
- ColdFusion and Azure Blob
- ColdFusion and Azure Service Bus
- Multi-cloud storage services
- Multi-cloud RDS databases
- ColdFusion and Azure Cosmos DB
Description
Defines a function that you can call in CFML. Required to define ColdFusion component methods.
History
ColdFusion (2018 release): It is no longer necessary to set the access attribute to "remote" in case of a REST-based function.
ColdFusion 10: Added the attributes- restPath, httpMethod, produces, and consumes.
ColdFusion 8:
- Added returnformat , secureJSON, and verifyClient attributes
- Added component as a valid value for the ReturnType attribute.
ColdFusion MX 7: Added the description attribute, and added the XML value to the returntype attribute.ColdFusion MX: Added this tag.
Category
See also
cfargument, cfcomponent, cfinterface, cfinvoke, cfinvokeargument, cfobject, cfproperty, cfreturn, SerializeJSON
Syntax
<cffunction name = "method name" access = "method access" consumes="MIME types" description = "function description" displayName = "name" httpMethod="GET|PUT|POST|DELETE" hint = "hint text" output = "yes|no" produces="MIME type" modifier="abstract|final|static" returnFormat = "not specified|JSON|plain|WDDX" returnType = "data type" roles = "securityRoles" restPath="sub-resource path" secureJSON = "yes|no" verifyClient = "no|yes">
Attributes
Attribute |
Req/Opt |
Default |
Description |
|---|---|---|---|
name |
Required |
|
A string; a component method that is used in the cfcomponent tag. |
access |
Optional |
public |
The client security context from which the method can be invoked. The following values are valid:
|
description |
Optional |
|
Supplies a short text description of the function. |
displayname |
Optional |
|
Meaningful only for CFC method parameters. A value to be displayed in parentheses following the function name when using introspection to show information about the CFC. |
hint |
Optional |
|
Meaningful only for CFC method parameters. Text to be displayed when using introspection to show information about the CFC. The hint attribute value follows the syntax line in the function description. |
output |
Optional |
Function body is processed as standard CFML |
Specifies under which conditions the function can generate HTML output. · yes: the entire function body is processed as if it were in a cfoutput tag. Variables names surrounded by number signs (#) are automatically replaced with their values. · no: the function is processed as if it were within a cfsilent tag. |
returnformat |
|
Return as WDDX or XML; see description. |
The format in which to return values to a remote caller. This attribute has no effect on values returned to a local caller. · json : serialize the return value into JSON format before returning it remotely. · wddx : serialize the return value into WDDX format before returning it remotely. · plain: ensure that the return value is a type that ColdFusion can convert directly to a string, and return the string value without serialization. Valid types include all simple types, such as numbers, and XML objects. If the return value is a complex type, such as an array, or a binary value, ColdFusion generates an error. If you specify a returntype attribute, its value must be any, boolean, date, guid , numeric, string, uuid , variablename , or XML; otherwise, ColdFusion generates an error. |
| restpath | Optional | String | Specify to use a sub- resource path for the CFC. You can also include regular expressions in the path. |
returnType |
Required for a web service; Optional, otherwise. |
any |
String; a type name; data type of the function return value: · any · array · binary · boolean · component: the return value must be a ColdFusion component. · date · function · guid : the argument must be a UUID or GUID of the form xxxxxxxx - xxxx - xxxx - xxxx - xxxxxxxxxxxx where each_ x_ is a character that represents a hexadecimal number (0-9A-F). · numeric · query · string · struct · uuid : the argument must be a ColdFusion UUID of the form xxxxxxxx - xxxx - xxxx - xxxxxxxxxxxxxxxx where each_ x_ is a character that represents a hexadecimal number (0-9A-F). · variableName: a string formatted according to ColdFusion variable naming conventions. · void: does not return a value. · xml : allows web service functions to return CFML XML objects and XML strings. · A component name: If the returntype attribute value is not one of the preceding items, ColdFusion treats it as the name of a ColdFusion component. When the function executes, it generates an error if the value that is returned is not a CFC with the specified name. |
roles |
Optional |
"" (empty) |
A comma-delimited list of ColdFusion security roles that can invoke the method. Only users who are logged in with the specified roles can execute the function. If this attribute is omitted, all users can invoke the method. |
secureJSON |
Optional |
See Description |
A Boolean value that specifies whether to add a security prefix in front of any value that the function returns in JSON-format in response to a remote call. The default value is the value of any This.secureJSON variable in the Application.cfc file or the secureJSON attribute of the cfapplication tag, or if there is no{{secureJSON}} application setting, the Prefix Serialized JSON setting in the Administrator Server Settings > Settings page, which defaults to false. |
verifyClient |
Optional |
no |
A Boolean value that specifies whether to require remote function calls to include an encrypted security token. For use with ColdFusion AJAX applications only. For more information see Improving security in Ajax programming rules and techniques in the Developing ColdFusion Applications. |
restPath |
Optional |
|
Specify to use a sub- resource path for the CFC. |
httpMethod |
|
|
The HTTP method to use, must be one of the following: · GET: Requests information from the server. Any data that the server requires to identify the requested information must be in the URL or in {{cfhttp type="URL"}}tag. · POST: Sends information to the server for processing. Requires one or more cfhttpparam tags. Often used for submitting form-like data. · PUT: Requests the server to store the message body at the specified URL. Use this method to send files to the server. · DELETE: Requests the server to delete the specified URL. · HEAD: Identical to the GET method, but the server does not send a message body in the response. Use this method for testing hypertext links for validity and accessibility, determining the type or modification time of a document, or determining the type of server. If you have not specified HEAD, by default, GET method is called. However, message body is not sent in the response. · OPTIONS: A request for information about the communication options available for the server or the specified URL. This method enables the ColdFusion application to determine the options and requirements associated with a URL, or the capabilities of a server, without requesting any additional activity by the server. If you have not specified OPTIONS, then ColdFusion sends a response. |
produces |
Optional |
/ |
Comma-separated list of acceptable MIME types. Used to specify the MIME media type of representation a resource can produce, for example, {{produces= "text /plain ,text / html "}}If a resource can produce more than one MIME media type, the function chosen corresponds to the most acceptable media type as declared by the client. Note |
consumes |
Optional |
/ |
Comma-separated list of acceptable MIME types, for example consumes="text/plain,text/ html ".Used to specify which MIME media types of representation a resource can accept, or consume, from the client. This attribute overrides the same attribute at the component level. |
modifier: Denotes the function as abstract (implementation must be defined in extended component), static (does not access instance variables in the component), or final (implementation cannot be extended).
Possible values are:
- abstract
- final
- static
Usage
The cffunction tag can define a function that you call in the same manner as a ColdFusion built-in function. To define a ColdFusion component (CFC) method, use a cffunction tag. The following example shows cffunction tag attributes for a simple CFC method that returns a ColdFusion Query object.
<cffunction name="getEmployees" access="remote" returnType="query" hint="This query returns all records in the employee database. It candrill-down or narrow the search, based on optional input parameters.">
For detailed information on using the cffunction tag for ColdFusion components, see Building and Using ColdFusion Components in the Developing ColdFusion Applications.
If you specify returnformat="json" and the function returns a query, ColdFusion serializes the query into a JSON Object with two entries, and array of column names, and an array of column data arrays. For more information see SerializeJSON.
If you specify a roles attribute, the function executes only if a user is logged in and belongs to one of the specified roles.
If you specify variableName for the returnType attribute, the function must return a string that is in ColdFusion variable name format; that is, the function must return a string that starts with a letter, underscore, or Unicode currency symbol, and consist of letters, numbers, and underscores (_), periods, and Unicode currency symbols, only. ColdFusion does not check whether the value corresponds to an existing ColdFusion variable.
Example
<cfcomponent> <cffunction name="getEmp"> <cfquery name="empQuery" datasource="ExampleApps" > SELECT FIRSTNAME, LASTNAME, EMAIL FROM tblEmployees </cfquery> <cfreturn empQuery> </cffunction> <cffunction name="getDept"> <cfquery name="deptQuery" datasource="ExampleApps" > SELECT * FROM tblDepartments </cfquery> <cfreturn deptQuery> </cffunction> </cfcomponent>
Example
<!--- component with attributes rest and restpath --->
<cfcomponent rest="true"
restpath="/crudService">
<!--- handle GET request (httpmethod),
take argument in restpath(restpath={customerID}),
return query data in json format(produces=text/json) --->
<cffunction name="getHandlerJSON"
access="remote"
httpmethod="GET"
restpath="{customerID}"
returntype="query"
produces="application/json">
<cfargument name="customerID"
required="true"
restargsource="Path"
type="numeric"/>
<cfset myQuery = queryNew("id,name",
"Integer,varchar",
[[1, "John"], [2, "Doe"]])>
<cfquery dbtype="query"
name="resultQuery">
select * from myQuery where id = #arguments.customerID#
</cfquery>
<cfreturn resultQuery>
</cffunction>
</cfcomponent>
Example
<cffunction name="getFullName" output="false" access="public" returnType="string">
<cfargument name="firstName" type="string" required="false" default="" />
<cfargument name="lastName" type="string" required="false" default="" />
<cfset var fullName = arguments.firstName & " " & arguments.lastname />
<cfreturn fullName />
</cffunction>
<cfset fullName = getFullName(firstName="John", lastName="Adams") />
<cfoutput>
Good morning, #fullName#!
</cfoutput>
Real-world uses of the cffunction tag
User authentication service
A web application needs user authentication to protect admin areas and personalize user experience.
Problem
- Need to verify user credentials
- Track logged-in users across page requests
- Provide login/logout functionality
- Check authentication status
Solution
Create a ColdFusion component with authentication methods using sessions.
Application.cfc
<cfcomponent output="false">
<cfset this.name = "AuthDemo">
<cfset this.sessionManagement = true>
<cfset this.sessionTimeout = createTimeSpan(0, 0, 30, 0)>
</cfcomponent>
UserAuth.cfc
<cffunction name="login" access="public" returntype="struct">
<cfargument name="username" type="string" required="true">
<cfargument name="password" type="string" required="true">
<cfset var result = {success: false, message: ""}>
<!--- Simple validation: admin/admin123 --->
<cfif arguments.username EQ "admin" AND arguments.password EQ "admin123">
<cfset session.user = {
username: arguments.username,
loginTime: now()
}>
<cfset result.success = true>
<cfset result.message = "Login successful!">
<cfelse>
<cfset result.message = "Invalid username or password">
</cfif>
<cfreturn result>
</cffunction>
<cffunction name="isLoggedIn" access="public" returntype="boolean">
<cfreturn structKeyExists(session, "user")>
</cffunction>
<cffunction name="logout" access="public" returntype="void">
<cfif structKeyExists(session, "user")>
<cfset structDelete(session, "user")>
</cfif>
</cffunction>
<cffunction name="getUser" access="public" returntype="struct">
<cfif isLoggedIn()>
<cfreturn session.user>
<cfelse>
<cfreturn {username: "Guest"}>
</cfif>
</cffunction>
</cfcomponent>
demo.cfm
<cfscript>
auth = createObject("component", "UserAuth");
// Handle login
if (isDefined("form.username")) {
loginResult = auth.login(form.username, form.password);
}
// Handle logout
if (isDefined("url.logout")) {
auth.logout();
}
</cfscript>
<!DOCTYPE html>
<html>
<head>
<title>User Authentication Demo</title>
<style>
body { font-family: Arial; max-width: 600px; margin: 50px auto; padding: 20px; }
.success { background: ##e8f5e9; border: 2px solid ##4caf50; padding: 20px; margin: 20px 0; border-radius: 5px; }
.error { background: ##ffebee; border: 2px solid ##f44336; padding: 20px; margin: 20px 0; border-radius: 5px; }
.info { background: ##e3f2fd; border: 2px solid ##2196f3; padding: 20px; margin: 20px 0; border-radius: 5px; }
input[type="text"], input[type="password"] { padding: 10px; width: 100%; margin: 10px 0; }
button { padding: 12px 30px; background: ##4caf50; color: white; border: none; border-radius: 5px; cursor: pointer; }
.logout-btn { background: ##f44336; }
</style>
</head>
<body>
<h1>🔐 User Authentication Demo</h1>
<!--- Show login result --->
<cfif isDefined("loginResult")>
<div class="<cfoutput>#loginResult.success ? 'success' : 'error'#</cfoutput>">
<cfoutput>#loginResult.message#</cfoutput>
</div>
</cfif>
<!--- Show current status --->
<div class="info">
<h3>Current Status</h3>
<cfif auth.isLoggedIn()>
<cfset currentUser = auth.getUser()>
<cfoutput>
<p><strong>Status:</strong> ✓ Logged In</p>
<p><strong>Username:</strong> #currentUser.username#</p>
<p><strong>Login Time:</strong> #dateTimeFormat(currentUser.loginTime, "yyyy-mm-dd HH:nn:ss")#</p>
<p><a href="?logout=true"><button class="logout-btn">Logout</button></a></p>
</cfoutput>
<cfelse>
<p><strong>Status:</strong> ✗ Not Logged In</p>
</cfif>
</div>
<!--- Show login form if not logged in --->
<cfif NOT auth.isLoggedIn()>
<h2>Login Form</h2>
<form method="post">
<div>
<label><strong>Username:</strong></label>
<input type="text" name="username" value="admin" required>
<small>Use: admin</small>
</div>
<div>
<label><strong>Password:</strong></label>
<input type="password" name="password" value="admin123" required>
<small>Use: admin123</small>
</div>
<button type="submit">Login</button>
</form>
</cfif>
<div style="margin-top: 30px; padding: 15px; background: ##f5f5f5; border-radius: 5px;">
<h4>Component Methods:</h4>
<ul>
<li><strong>login(username, password)</strong> - Authenticate user</li>
<li><strong>isLoggedIn()</strong> - Check if user is logged in</li>
<li><strong>logout()</strong> - Log out current user</li>
<li><strong>getUser()</strong> - Get current user info</li>
</ul>
</div>
</body>
</html>
Data validation component
Forms and APIs need to validate user input consistently across the application.
Problem
- Email addresses must be properly formatted
- Phone numbers must have exactly 10 digits
- Zip codes must follow US format
- Required fields must not be empty
- Text must meet length requirements
Solution
Create a reusable validation component with specific validation methods.
Application.cfc
<cfcomponent output="false">
<cfset this.name = "ValidationDemo">
</cfcomponent>
Validator.cfc
<cfcomponent>
<cffunction name="validateEmail" access="public" returntype="boolean">
<cfargument name="email" type="string" required="true">
<cfreturn reFind("^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$", trim(arguments.email)) GT 0>
</cffunction>
<cffunction name="validatePhone" access="public" returntype="boolean">
<cfargument name="phone" type="string" required="true">
<cfset var cleanPhone = reReplace(arguments.phone, "[^0-9]", "", "ALL")>
<cfreturn len(cleanPhone) EQ 10>
</cffunction>
<cffunction name="validateZipCode" access="public" returntype="boolean">
<cfargument name="zipCode" type="string" required="true">
<cfreturn reFind("^\d{5}(-\d{4})?$", trim(arguments.zipCode)) GT 0>
</cffunction>
<cffunction name="validateRequired" access="public" returntype="struct">
<cfargument name="value" type="string" required="true">
<cfargument name="fieldName" type="string" required="false" default="Field">
<cfset var result = {valid: true, message: ""}>
<cfif len(trim(arguments.value)) EQ 0>
<cfset result.valid = false>
<cfset result.message = "#arguments.fieldName# is required">
</cfif>
<cfreturn result>
</cffunction>
<cffunction name="validateLength" access="public" returntype="struct">
<cfargument name="value" type="string" required="true">
<cfargument name="minLength" type="numeric" required="true">
<cfargument name="maxLength" type="numeric" required="true">
<cfset var result = {valid: true, message: ""}>
<cfset var valueLength = len(trim(arguments.value))>
<cfif valueLength LT arguments.minLength>
<cfset result.valid = false>
<cfset result.message = "Must be at least #arguments.minLength# characters">
<cfelseif valueLength GT arguments.maxLength>
<cfset result.valid = false>
<cfset result.message = "Cannot exceed #arguments.maxLength# characters">
</cfif>
<cfreturn result>
</cffunction>
</cfcomponent>
demo.cfm
<cfscript>
validator = createObject("component", "Validator");
// Test data
testData = {
validEmail: "john@example.com",
invalidEmail: "not-an-email",
validPhone: "(555) 123-4567",
invalidPhone: "123",
validZip: "12345",
invalidZip: "ABC"
};
</cfscript>
<!DOCTYPE html>
<html>
<head>
<title>Data Validation Demo</title>
<style>
body { font-family: Arial; max-width: 800px; margin: 50px auto; padding: 20px; }
table { width: 100%; border-collapse: collapse; margin: 20px 0; }
th, td { padding: 12px; border: 1px solid ##ddd; text-align: left; }
th { background: ##2196f3; color: white; }
.valid { color: ##4caf50; font-weight: bold; }
.invalid { color: ##f44336; font-weight: bold; }
.info { background: ##e3f2fd; padding: 15px; margin: 20px 0; border-radius: 5px; }
</style>
</head>
<body>
<h1>✅ Data Validation Demo</h1>
<h2>Email Validation</h2>
<table>
<tr>
<th>Email</th>
<th>Valid?</th>
</tr>
<cfoutput>
<tr>
<td>#testData.validEmail#</td>
<td class="#validator.validateEmail(testData.validEmail) ? 'valid' : 'invalid'#">
#validator.validateEmail(testData.validEmail) ? '✓ Valid' : '✗ Invalid'#
</td>
</tr>
<tr>
<td>#testData.invalidEmail#</td>
<td class="#validator.validateEmail(testData.invalidEmail) ? 'valid' : 'invalid'#">
#validator.validateEmail(testData.invalidEmail) ? '✓ Valid' : '✗ Invalid'#
</td>
</tr>
</cfoutput>
</table>
<h2>Phone Number Validation</h2>
<table>
<tr>
<th>Phone</th>
<th>Valid?</th>
</tr>
<cfoutput>
<tr>
<td>#testData.validPhone#</td>
<td class="#validator.validatePhone(testData.validPhone) ? 'valid' : 'invalid'#">
#validator.validatePhone(testData.validPhone) ? '✓ Valid (10 digits)' : '✗ Invalid'#
</td>
</tr>
<tr>
<td>#testData.invalidPhone#</td>
<td class="#validator.validatePhone(testData.invalidPhone) ? 'valid' : 'invalid'#">
#validator.validatePhone(testData.invalidPhone) ? '✓ Valid' : '✗ Invalid (too short)'#
</td>
</tr>
</cfoutput>
</table>
<h2>Zip Code Validation</h2>
<table>
<tr>
<th>Zip Code</th>
<th>Valid?</th>
</tr>
<cfoutput>
<tr>
<td>#testData.validZip#</td>
<td class="#validator.validateZipCode(testData.validZip) ? 'valid' : 'invalid'#">
#validator.validateZipCode(testData.validZip) ? '✓ Valid' : '✗ Invalid'#
</td>
</tr>
<tr>
<td>#testData.invalidZip#</td>
<td class="#validator.validateZipCode(testData.invalidZip) ? 'valid' : 'invalid'#">
#validator.validateZipCode(testData.invalidZip) ? '✓ Valid' : '✗ Invalid'#
</td>
</tr>
</cfoutput>
</table>
<h2>Advanced Validations</h2>
<cfset requiredCheck = validator.validateRequired("", "Username")>
<cfset lengthCheck = validator.validateLength("Hi", 5, 20)>
<div class="info">
<h3>Required Field Check</h3>
<cfoutput>
<p><strong>Value:</strong> "" (empty)</p>
<p><strong>Result:</strong>
<span class="#requiredCheck.valid ? 'valid' : 'invalid'#">
#requiredCheck.valid ? '✓ Valid' : '✗ ' & requiredCheck.message#
</span>
</p>
</cfoutput>
</div>
<div class="info">
<h3>Length Validation</h3>
<cfoutput>
<p><strong>Value:</strong> "Hi" (must be 5-20 characters)</p>
<p><strong>Result:</strong>
<span class="#lengthCheck.valid ? 'valid' : 'invalid'#">
#lengthCheck.valid ? '✓ Valid' : '✗ ' & lengthCheck.message#
</span>
</p>
</cfoutput>
</div>
</body>
</html>
Shopping cart component
E-commerce websites need shopping carts to allow customers to select products before checkout.
Problem
- Track items selected by user
- Calculate totals across page requests
- Allow adding/removing items
- Display cart contents
- Persist cart in session
Solution
Create a session-based shopping cart component with methods to manage items.
Application.cfc
<cfcomponent output="false">
<cfset this.name = "ShoppingCartDemo">
<cfset this.sessionManagement = true>
<cfset this.sessionTimeout = createTimeSpan(0, 1, 0, 0)>
</cfcomponent>
Cart.cfc
<cfcomponent>
<cffunction name="init" access="public" returntype="any">
<cfif NOT structKeyExists(session, "cart")>
<cfset session.cart = []>
</cfif>
<cfreturn this>
</cffunction>
<cffunction name="addItem" access="public" returntype="void">
<cfargument name="productID" type="numeric" required="true">
<cfargument name="productName" type="string" required="true">
<cfargument name="price" type="numeric" required="true">
<!--- Check if item exists --->
<cfset var found = false>
<cfloop array="#session.cart#" index="item">
<cfif item.productID EQ arguments.productID>
<cfset item.quantity = item.quantity + 1>
<cfset found = true>
<cfbreak>
</cfif>
</cfloop>
<!--- Add new item if not found --->
<cfif NOT found>
<cfset arrayAppend(session.cart, {
productID: arguments.productID,
productName: arguments.productName,
price: arguments.price,
quantity: 1
})>
</cfif>
</cffunction>
<cffunction name="removeItem" access="public" returntype="void">
<cfargument name="productID" type="numeric" required="true">
<cfloop index="i" from="1" to="#arrayLen(session.cart)#">
<cfif session.cart[i].productID EQ arguments.productID>
<cfset arrayDeleteAt(session.cart, i)>
<cfbreak>
</cfif>
</cfloop>
</cffunction>
<cffunction name="getItems" access="public" returntype="array">
<cfreturn session.cart>
</cffunction>
<cffunction name="getTotal" access="public" returntype="numeric">
<cfset var total = 0>
<cfloop array="#session.cart#" index="item">
<cfset total = total + (item.price * item.quantity)>
</cfloop>
<cfreturn total>
</cffunction>
<cffunction name="getItemCount" access="public" returntype="numeric">
<cfset var count = 0>
<cfloop array="#session.cart#" index="item">
<cfset count = count + item.quantity>
</cfloop>
<cfreturn count>
</cffunction>
<cffunction name="clear" access="public" returntype="void">
<cfset session.cart = []>
</cffunction>
</cfcomponent>
demo.cfm
<cfscript>
cart = createObject("component", "Cart").init();
// Handle add to cart
if (isDefined("url.add")) {
cart.addItem(url.productID, url.name, url.price);
}
// Handle remove from cart
if (isDefined("url.remove")) {
cart.removeItem(url.productID);
}
// Handle clear cart
if (isDefined("url.clear")) {
cart.clear();
}
// Sample products
products = [
{id: 1, name: "Laptop", price: 999.99},
{id: 2, name: "Mouse", price: 29.99},
{id: 3, name: "Keyboard", price: 79.99},
{id: 4, name: "Monitor", price: 299.99}
];
</cfscript>
<!DOCTYPE html>
<html>
<head>
<title>Shopping Cart Demo</title>
<style>
body { font-family: Arial; max-width: 900px; margin: 50px auto; padding: 20px; }
.products { display: grid; grid-template-columns: repeat(2, 1fr); gap: 20px; margin: 20px 0; }
.product { background: ##f5f5f5; padding: 20px; border-radius: 5px; }
.price { font-size: 24px; color: ##4caf50; font-weight: bold; }
.btn { padding: 10px 20px; background: ##4caf50; color: white; text-decoration: none; border-radius: 5px; display: inline-block; }
.btn-remove { background: ##f44336; }
.btn-clear { background: ##ff9800; }
table { width: 100%; border-collapse: collapse; margin: 20px 0; }
th, td { padding: 12px; border: 1px solid ##ddd; text-align: left; }
th { background: ##2196f3; color: white; }
.cart-summary { background: ##e3f2fd; padding: 20px; border-radius: 5px; margin: 20px 0; }
</style>
</head>
<body>
<h1>🛒 Shopping Cart Demo</h1>
<h2>Products</h2>
<div class="products">
<cfloop array="#products#" index="product">
<cfoutput>
<div class="product">
<h3>#product.name#</h3>
<p class="price">$#numberFormat(product.price, "0.00")#</p>
<a href="?add=true&productID=#product.id#&name=#urlEncodedFormat(product.name)#&price=#product.price#" class="btn">
Add to Cart
</a>
</div>
</cfoutput>
</cfloop>
</div>
<h2>Your Cart</h2>
<cfset cartItems = cart.getItems()>
<cfif arrayLen(cartItems) GT 0>
<table>
<tr>
<th>Product</th>
<th>Price</th>
<th>Quantity</th>
<th>Subtotal</th>
<th>Action</th>
</tr>
<cfloop array="#cartItems#" index="item">
<cfoutput>
<tr>
<td>#item.productName#</td>
<td>$#numberFormat(item.price, "0.00")#</td>
<td>#item.quantity#</td>
<td><strong>$#numberFormat(item.price * item.quantity, "0.00")#</strong></td>
<td><a href="?remove=true&productID=#item.productID#" class="btn btn-remove">Remove</a></td>
</tr>
</cfoutput>
</cfloop>
</table>
<div class="cart-summary">
<cfoutput>
<h3>Cart Summary</h3>
<p><strong>Total Items:</strong> #cart.getItemCount()#</p>
<p><strong>Total Amount:</strong> <span style="font-size: 24px; color: ##4caf50;">$#numberFormat(cart.getTotal(), "0.00")#</span></p>
<a href="?clear=true" class="btn btn-clear">Clear Cart</a>
</cfoutput>
</div>
<cfelse>
<p style="padding: 20px; background: ##f5f5f5; border-radius: 5px;">Your cart is empty. Add some products above!</p>
</cfif>
</body>
</html>