- 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
Creates a parameter definition within a component definition. Defines a function argument. Used within a cffunction tag.
Category
Syntax
<cfargument name="string" default="default value" displayname="descriptive name" hint="extended description" required="yes|no" type="data type">
See also
cfcomponent, cffunction, cfinterface, cfinvoke, cfinvokeargument, cfobject, cfproperty, cfreturn
History
- ColdFusion (2018 release): Added the data type integer for the argument type.
- ColdFusion 10: Added the following REST attributes: restArgSource, restArgName}}
- ColdFusion 8: Added {{component as a valid value for the ReturnType attribute.
- ColdFusion MX 7: Added the xml value of type attribute.ColdFusion MX: Added this tag.
Attributes
Attribute |
Req/Opt |
Default |
Description |
|---|---|---|---|
name |
Required |
|
String; an argument name. |
default |
Optional |
|
If no argument is passed, specifies a default argument value. |
displayname |
Optional |
name attribute value |
Meaningful only for CFC method parameters. A value to display when using introspection to show information about the CFC. |
hint |
Optional |
|
Meaningful only for CFC method parameters. Text to display when using introspection to show information about the CFC. The hint attribute value follows the displayname attribute value in the parameter description line. Use this attribute to describe the purpose of the parameter. |
required |
Optional |
no |
Note: All arguments are required when invoked as a web service, irrespective of how they are defined.Specifies whether the parameter is required to execute the component method. The parameter is not required if you specify a default attribute.
|
restArgSource |
Optional |
|
One of the following:
|
restArgName |
Optional |
|
The name that can be mapped to the argument name. |
type |
Optional |
any |
String; a type name; data type of the argument.
|
Usage
This tag must be in a cffunction tag, before any other tags in the cffunction tag body.Arguments that are passed when a method is invoked can be accessed from the method body in the following ways:
- With shorthand syntax: #myargument# (This example accesses the argument myargument .)
- Using the arguments scope as an array: #arguments[1]# (This example accesses the first defined argument in the cffunction .)
- Using the arguments scope as a struct: #arguments.myargument# (This example accesses the argument myargument in the array.)
Example
<!--- This example defines a function that takes a course number parameter and returns the course description. ---> <cffunction name="getDescription"> <!--- Identify argument. ---> <cfargument name="Course_Number" type="numeric" required="true"> <!--- Use the argument to get a course description from the database. ---> <cfquery name="Description" datasource="cfdocexamples"> SELECT Descript FROM Courses WHERE Number = '#Course_Number#' </cfquery> <!--- Specify the variable that the function returns. ---> <cfreturn Description.Descript> </cffunction>
Real-world uses of the cfargument tag
Online user registration system
Your company's website requires new users to register with their personal information. The registration form collects username, email, password, and optional phone number. The system needs to validate all input data before creating user accounts, ensuring data integrity and security.
Problem statement
- User registration requires multiple fields with different data types
- Some fields are required (username, email, password)
- Some fields are optional (phone number, age)
- Need strong type validation to prevent invalid data
- Must validate email format
Solution
The cfargument tag within cfargument ensures arguments are correct data type (string, numeric, email), provides fallback values for optional parameters, and validates types before the function executes.
<!--- Define registration function with cfargument validation --->
<cffunction name="registerUser" returntype="struct" output="false">
<cfargument name="username" type="string" required="true" hint="User's login name">
<cfargument name="email" type="email" required="true" hint="User's email address">
<cfargument name="password" type="string" required="true" hint="User's password">
<cfargument name="phoneNumber" type="string" required="false" default="" hint="Optional phone number">
<cfargument name="age" type="numeric" required="false" default="0" hint="Optional age">
<!--- Simulate user registration --->
<cfset var result = {}>
<cfset result.success = true>
<cfset result.message = "User registered successfully">
<cfset result.username = arguments.username>
<cfset result.email = arguments.email>
<cfset result.phoneNumber = arguments.phoneNumber>
<cfset result.age = arguments.age>
<cfset result.registeredAt = now()>
<cflog file="registration" type="information" text="New user registered: #arguments.username# (#arguments.email#)">
<cfreturn result>
</cffunction>
<h1>User Registration Form Validation Demo</h1>
<p><strong>What This Demo Shows:</strong> How to use cfargument for validating function parameters.</p>
<hr>
<h2>Example 1: Valid Registration with All Required Fields</h2>
<cftry>
<cfset registrationResult = registerUser(
username="johndoe",
email="john@example.com",
password="SecurePass123"
)>
<p><strong>✓ Registration Successful</strong></p>
<cfoutput>
<p>Username: #registrationResult.username#</p>
<p>Email: #registrationResult.email#</p>
<p>Phone: #registrationResult.phoneNumber EQ "" ? "(not provided)" : registrationResult.phoneNumber#</p>
<p>Age: #registrationResult.age EQ 0 ? "(not provided)" : registrationResult.age#</p>
<p>Registered: #dateTimeFormat(registrationResult.registeredAt, "yyyy-mm-dd HH:nn:ss")#</p>
</cfoutput>
<cfcatch type="any">
<p><strong>✗ Registration Failed:</strong></p>
<cfoutput>
<p>Error: #cfcatch.message#</p>
</cfoutput>
</cfcatch>
</cftry>
<hr>
<h2>Example 2: Registration with Optional Parameters</h2>
<cftry>
<cfset registrationResult2 = registerUser(
username="janedoe",
email="jane@example.com",
password="MyPassword456",
phoneNumber="555-0123",
age=28
)>
<p><strong>✓ Registration Successful (With Optional Fields)</strong></p>
<cfoutput>
<p>Username: #registrationResult2.username#</p>
<p>Email: #registrationResult2.email#</p>
<p>Phone: #registrationResult2.phoneNumber#</p>
<p>Age: #registrationResult2.age#</p>
<p>Registered: #dateTimeFormat(registrationResult2.registeredAt, "yyyy-mm-dd HH:nn:ss")#</p>
</cfoutput>
<cfcatch type="any">
<p><strong>✗ Registration Failed:</strong></p>
<cfoutput>
<p>Error: #cfcatch.message#</p>
</cfoutput>
</cfcatch>
</cftry>
<hr>
<h2>Example 3: Invalid Email Format (Validation Error)</h2>
<cftry>
<cfset registrationResult3 = registerUser(
username="testuser",
email="invalid-email-format",
password="TestPass789"
)>
<p><strong>✓ Registration Successful</strong></p>
<cfoutput>
<p>Username: #registrationResult3.username#</p>
</cfoutput>
<cfcatch type="any">
<p><strong>✗ Registration Failed (Expected):</strong></p>
<cfoutput>
<p style="color: red;">Error Type: #cfcatch.type#</p>
<p style="color: red;">Message: #cfcatch.message#</p>
<p>The email validation failed because cfargument type="email" enforces proper email format.</p>
</cfoutput>
</cfcatch>
</cftry>
<hr>
<h2>Example 4: Missing Required Parameter</h2>
<cftry>
<!--- Intentionally omit required 'password' parameter --->
<cfset registrationResult4 = registerUser(
username="testuser2",
email="test2@example.com"
)>
<p><strong>✓ Registration Successful</strong></p>
<cfcatch type="any">
<p><strong>✗ Registration Failed (Expected):</strong></p>
<cfoutput>
<p style="color: red;">Error Type: #cfcatch.type#</p>
<p style="color: red;">Message: #cfcatch.message#</p>
<p>The registration failed because 'password' is a required parameter (required="true").</p>
</cfoutput>
</cfcatch>
</cftry>
<hr>
Online store pricing system
Your e-commerce platform needs to calculate final product prices including discounts, taxes, and shipping. The pricing function must handle various scenarios: percentage discounts, flat-rate discounts, tax rates varying by region, and optional shipping charges. Different product types may have different calculation rules.
Problem statement
- Need to calculate prices with multiple optional parameters
- Discount can be percentage or flat amount
- Tax rates vary by customer location
- Shipping is optional (digital products don't need shipping)
Solution
The cfargument tag provides numerical type validation, sets the standard tax rate and shipping as defaults, and controls whether to apply shipping or discounts.
<!--- Define price calculation function with multiple optional arguments --->
<cffunction name="calculatePrice" returntype="struct" output="false">
<cfargument name="basePrice" type="numeric" required="true" hint="Original product price">
<cfargument name="quantity" type="numeric" required="true" hint="Number of items">
<cfargument name="discountPercent" type="numeric" required="false" default="0" hint="Discount percentage (0-100)">
<cfargument name="taxRate" type="numeric" required="false" default="8.5" hint="Tax rate percentage">
<cfargument name="shippingCost" type="numeric" required="false" default="9.99" hint="Shipping cost">
<cfargument name="includeShipping" type="boolean" required="false" default="true" hint="Whether to add shipping">
<!--- Calculate pricing breakdown --->
<cfset var result = {}>
<cfset result.basePrice = arguments.basePrice>
<cfset result.quantity = arguments.quantity>
<cfset result.subtotal = arguments.basePrice * arguments.quantity>
<!--- Apply discount --->
<cfset result.discountPercent = arguments.discountPercent>
<cfset result.discountAmount = result.subtotal * (arguments.discountPercent / 100)>
<cfset result.afterDiscount = result.subtotal - result.discountAmount>
<!--- Apply tax --->
<cfset result.taxRate = arguments.taxRate>
<cfset result.taxAmount = result.afterDiscount * (arguments.taxRate / 100)>
<!--- Add shipping if applicable --->
<cfset result.includeShipping = arguments.includeShipping>
<cfset result.shippingCost = arguments.includeShipping ? arguments.shippingCost : 0>
<!--- Calculate final total --->
<cfset result.total = result.afterDiscount + result.taxAmount + result.shippingCost>
<cfreturn result>
</cffunction>
<h1>E-commerce Price Calculator Demo</h1>
<p><strong>What This Demo Shows:</strong> How to use cfargument with numeric types and default values for flexible calculations.</p>
<hr>
<h2>Example 1: Basic Price Calculation (Using Defaults)</h2>
<cftry>
<!--- Calculate price with minimal parameters - uses default tax and shipping --->
<cfset priceResult = calculatePrice(
basePrice=29.99,
quantity=2
)>
<p><strong>✓ Price Calculated (With Default Tax & Shipping)</strong></p>
<table border="1" cellpadding="5" cellspacing="0" style="border-collapse: collapse;">
<cfoutput>
<tr><td><strong>Base Price:</strong></td><td>$#numberFormat(priceResult.basePrice, "0.00")#</td></tr>
<tr><td><strong>Quantity:</strong></td><td>#priceResult.quantity#</td></tr>
<tr><td><strong>Subtotal:</strong></td><td>$#numberFormat(priceResult.subtotal, "0.00")#</td></tr>
<tr><td><strong>Discount (#priceResult.discountPercent#%):</strong></td><td>-$#numberFormat(priceResult.discountAmount, "0.00")#</td></tr>
<tr><td><strong>After Discount:</strong></td><td>$#numberFormat(priceResult.afterDiscount, "0.00")#</td></tr>
<tr><td><strong>Tax (#priceResult.taxRate#%):</strong></td><td>+$#numberFormat(priceResult.taxAmount, "0.00")#</td></tr>
<tr><td><strong>Shipping:</strong></td><td>+$#numberFormat(priceResult.shippingCost, "0.00")#</td></tr>
<tr style="background-color: ##e6ffe6; font-weight: bold;"><td><strong>TOTAL:</strong></td><td>$#numberFormat(priceResult.total, "0.00")#</td></tr>
</cfoutput>
</table>
<cfcatch type="any">
<p><strong>✗ Error:</strong> <cfoutput>#cfcatch.message#</cfoutput></p>
</cfcatch>
</cftry>
<hr>
<h2>Example 2: With Discount Applied</h2>
<cftry>
<!--- Apply 15% discount --->
<cfset priceResult2 = calculatePrice(
basePrice=99.99,
quantity=1,
discountPercent=15,
taxRate=7.0
)>
<p><strong>✓ Price Calculated (15% Discount Applied)</strong></p>
<table border="1" cellpadding="5" cellspacing="0" style="border-collapse: collapse;">
<cfoutput>
<tr><td><strong>Base Price:</strong></td><td>$#numberFormat(priceResult2.basePrice, "0.00")#</td></tr>
<tr><td><strong>Quantity:</strong></td><td>#priceResult2.quantity#</td></tr>
<tr><td><strong>Subtotal:</strong></td><td>$#numberFormat(priceResult2.subtotal, "0.00")#</td></tr>
<tr style="background-color: ##ffe6e6;"><td><strong>Discount (#priceResult2.discountPercent#%):</strong></td><td>-$#numberFormat(priceResult2.discountAmount, "0.00")#</td></tr>
<tr><td><strong>After Discount:</strong></td><td>$#numberFormat(priceResult2.afterDiscount, "0.00")#</td></tr>
<tr><td><strong>Tax (#priceResult2.taxRate#%):</strong></td><td>+$#numberFormat(priceResult2.taxAmount, "0.00")#</td></tr>
<tr><td><strong>Shipping:</strong></td><td>+$#numberFormat(priceResult2.shippingCost, "0.00")#</td></tr>
<tr style="background-color: ##e6ffe6; font-weight: bold;"><td><strong>TOTAL:</strong></td><td>$#numberFormat(priceResult2.total, "0.00")#</td></tr>
</cfoutput>
</table>
<cfcatch type="any">
<p><strong>✗ Error:</strong> <cfoutput>#cfcatch.message#</cfoutput></p>
</cfcatch>
</cftry>
<hr>
<h2>Example 3: Digital Product (No Shipping)</h2>
<cftry>
<!--- Digital product - no shipping needed --->
<cfset priceResult3 = calculatePrice(
basePrice=49.99,
quantity=1,
discountPercent=20,
taxRate=0,
includeShipping=false
)>
<p><strong>✓ Price Calculated (Digital Product - No Shipping)</strong></p>
<table border="1" cellpadding="5" cellspacing="0" style="border-collapse: collapse;">
<cfoutput>
<tr><td><strong>Base Price:</strong></td><td>$#numberFormat(priceResult3.basePrice, "0.00")#</td></tr>
<tr><td><strong>Quantity:</strong></td><td>#priceResult3.quantity#</td></tr>
<tr><td><strong>Subtotal:</strong></td><td>$#numberFormat(priceResult3.subtotal, "0.00")#</td></tr>
<tr style="background-color: ##ffe6e6;"><td><strong>Discount (#priceResult3.discountPercent#%):</strong></td><td>-$#numberFormat(priceResult3.discountAmount, "0.00")#</td></tr>
<tr><td><strong>After Discount:</strong></td><td>$#numberFormat(priceResult3.afterDiscount, "0.00")#</td></tr>
<tr><td><strong>Tax (#priceResult3.taxRate#%):</strong></td><td>+$#numberFormat(priceResult3.taxAmount, "0.00")#</td></tr>
<tr style="background-color: ##f0f0f0;"><td><strong>Shipping:</strong></td><td>$#numberFormat(priceResult3.shippingCost, "0.00")# (Digital - No Shipping)</td></tr>
<tr style="background-color: ##e6ffe6; font-weight: bold;"><td><strong>TOTAL:</strong></td><td>$#numberFormat(priceResult3.total, "0.00")#</td></tr>
</cfoutput>
</table>
<cfcatch type="any">
<p><strong>✗ Error:</strong> <cfoutput>#cfcatch.message#</cfoutput></p>
</cfcatch>
</cftry>
<hr>
<h2>Example 4: Bulk Order with Custom Shipping</h2>
<cftry>
<!--- Bulk order with custom shipping --->
<cfset priceResult4 = calculatePrice(
basePrice=15.99,
quantity=10,
discountPercent=10,
taxRate=6.5,
shippingCost=25.00
)>
<p><strong>✓ Price Calculated (Bulk Order)</strong></p>
<table border="1" cellpadding="5" cellspacing="0" style="border-collapse: collapse;">
<cfoutput>
<tr><td><strong>Base Price:</strong></td><td>$#numberFormat(priceResult4.basePrice, "0.00")#</td></tr>
<tr><td><strong>Quantity:</strong></td><td>#priceResult4.quantity#</td></tr>
<tr><td><strong>Subtotal:</strong></td><td>$#numberFormat(priceResult4.subtotal, "0.00")#</td></tr>
<tr style="background-color: ##ffe6e6;"><td><strong>Discount (#priceResult4.discountPercent#%):</strong></td><td>-$#numberFormat(priceResult4.discountAmount, "0.00")#</td></tr>
<tr><td><strong>After Discount:</strong></td><td>$#numberFormat(priceResult4.afterDiscount, "0.00")#</td></tr>
<tr><td><strong>Tax (#priceResult4.taxRate#%):</strong></td><td>+$#numberFormat(priceResult4.taxAmount, "0.00")#</td></tr>
<tr><td><strong>Shipping (Bulk Rate):</strong></td><td>+$#numberFormat(priceResult4.shippingCost, "0.00")#</td></tr>
<tr style="background-color: ##e6ffe6; font-weight: bold;"><td><strong>TOTAL:</strong></td><td>$#numberFormat(priceResult4.total, "0.00")#</td></tr>
</cfoutput>
</table>
<cfcatch type="any">
<p><strong>✗ Error:</strong> <cfoutput>#cfcatch.message#</cfoutput></p>
</cfcatch>
</cftry>
<hr>
CRM Customer Database Search
Your Customer Relationship Management (CRM) system needs a flexible search function to find customers based on various criteria. Sales representatives need to search by name, email, phone, customer ID, or any combination. Some searches should be case-sensitive, others not. Results should be sortable and limitable.
Problem statement
- Multiple optional search criteria (name, email, phone, customer ID)
- Need case-insensitive search option
- Results should be sortable by different fields
- Need to limit the result count for performance
- Some parameters are strings, others are numeric
Solution
The cfargument tag ensures all search criteria are optional, controls case-sensitivity and matches type, and calls with any combination of arguments.
<!--- Define flexible customer search function --->
<cffunction name="searchCustomers" returntype="struct" output="false">
<cfargument name="customerID" type="numeric" required="false" default="0" hint="Customer ID">
<cfargument name="firstName" type="string" required="false" default="" hint="First name to search">
<cfargument name="lastName" type="string" required="false" default="" hint="Last name to search">
<cfargument name="email" type="string" required="false" default="" hint="Email address to search">
<cfargument name="phone" type="string" required="false" default="" hint="Phone number to search">
<cfargument name="caseInsensitive" type="boolean" required="false" default="true" hint="Case-insensitive search">
<cfargument name="maxResults" type="numeric" required="false" default="10" hint="Maximum results to return">
<!--- Mock customer database --->
<cfset var mockCustomers = [
{id: 1001, firstName: "John", lastName: "Smith", email: "john.smith@example.com", phone: "555-0101"},
{id: 1002, firstName: "Jane", lastName: "Johnson", email: "jane.johnson@example.com", phone: "555-0102"},
{id: 1003, firstName: "Robert", lastName: "Williams", email: "robert.w@example.com", phone: "555-0103"},
{id: 1004, firstName: "Mary", lastName: "Smith", email: "mary.smith@example.com", phone: "555-0104"},
{id: 1005, firstName: "Jennifer", lastName: "Brown", email: "jennifer.b@example.com", phone: "555-0105"}
]>
<cfset var results = []>
<cfset var searchCriteria = []>
<!--- Filter based on provided criteria --->
<cfloop array="#mockCustomers#" index="customer">
<cfset var matches = true>
<!--- Check customer ID if provided --->
<cfif arguments.customerID GT 0 AND customer.id NEQ arguments.customerID>
<cfset matches = false>
</cfif>
<!--- Check first name if provided --->
<cfif arguments.firstName NEQ "" AND matches>
<cfif arguments.caseInsensitive>
<cfif NOT findNoCase(arguments.firstName, customer.firstName)>
<cfset matches = false>
</cfif>
<cfelse>
<cfif NOT find(arguments.firstName, customer.firstName)>
<cfset matches = false>
</cfif>
</cfif>
</cfif>
<!--- Check last name if provided --->
<cfif arguments.lastName NEQ "" AND matches>
<cfif arguments.caseInsensitive>
<cfif NOT findNoCase(arguments.lastName, customer.lastName)>
<cfset matches = false>
</cfif>
<cfelse>
<cfif NOT find(arguments.lastName, customer.lastName)>
<cfset matches = false>
</cfif>
</cfif>
</cfif>
<!--- Check email if provided --->
<cfif arguments.email NEQ "" AND matches>
<cfif NOT findNoCase(arguments.email, customer.email)>
<cfset matches = false>
</cfif>
</cfif>
<!--- Check phone if provided --->
<cfif arguments.phone NEQ "" AND matches>
<cfif NOT find(arguments.phone, customer.phone)>
<cfset matches = false>
</cfif>
</cfif>
<!--- Add to results if matches --->
<cfif matches>
<cfset arrayAppend(results, customer)>
</cfif>
<!--- Stop if we reached max results --->
<cfif arrayLen(results) GTE arguments.maxResults>
<cfbreak>
</cfif>
</cfloop>
<!--- Build search criteria description --->
<cfif arguments.customerID GT 0>
<cfset arrayAppend(searchCriteria, "ID=#arguments.customerID#")>
</cfif>
<cfif arguments.firstName NEQ "">
<cfset arrayAppend(searchCriteria, "First Name=#arguments.firstName#")>
</cfif>
<cfif arguments.lastName NEQ "">
<cfset arrayAppend(searchCriteria, "Last Name=#arguments.lastName#")>
</cfif>
<cfif arguments.email NEQ "">
<cfset arrayAppend(searchCriteria, "Email=#arguments.email#")>
</cfif>
<cfif arguments.phone NEQ "">
<cfset arrayAppend(searchCriteria, "Phone=#arguments.phone#")>
</cfif>
<cfreturn {
results: results,
count: arrayLen(results),
searchCriteria: searchCriteria,
caseInsensitive: arguments.caseInsensitive,
maxResults: arguments.maxResults
}>
</cffunction>
<h1>Customer Search Function Demo</h1>
<p><strong>What This Demo Shows:</strong> How to use cfargument with multiple optional parameters for flexible searches.</p>
<hr>
<h2>Example 1: Search by Last Name</h2>
<cftry>
<cfset searchResult = searchCustomers(lastName="Smith")>
<p><strong>✓ Search Completed</strong></p>
<p>Search Criteria: <cfoutput>#arrayToList(searchResult.searchCriteria, ", ")#</cfoutput></p>
<p>Results Found: <cfoutput>#searchResult.count#</cfoutput></p>
<cfif searchResult.count GT 0>
<table border="1" cellpadding="5" cellspacing="0" style="border-collapse: collapse;">
<tr style="background-color: ##f0f0f0;">
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<cfloop array="#searchResult.results#" index="customer">
<cfoutput>
<tr>
<td>#customer.id#</td>
<td>#customer.firstName#</td>
<td><strong>#customer.lastName#</strong></td>
<td>#customer.email#</td>
<td>#customer.phone#</td>
</tr>
</cfoutput>
</cfloop>
</table>
</cfif>
<cfcatch type="any">
<p><strong>✗ Error:</strong> <cfoutput>#cfcatch.message#</cfoutput></p>
</cfcatch>
</cftry>
<hr>
<h2>Example 2: Search by Customer ID</h2>
<cftry>
<cfset searchResult2 = searchCustomers(customerID=1003)>
<p><strong>✓ Search Completed</strong></p>
<p>Search Criteria: <cfoutput>#arrayToList(searchResult2.searchCriteria, ", ")#</cfoutput></p>
<p>Results Found: <cfoutput>#searchResult2.count#</cfoutput></p>
<cfif searchResult2.count GT 0>
<cfset customer = searchResult2.results[1]>
<cfoutput>
<p><strong>Customer Details:</strong></p>
<ul>
<li>ID: #customer.id#</li>
<li>Name: #customer.firstName# #customer.lastName#</li>
<li>Email: #customer.email#</li>
<li>Phone: #customer.phone#</li>
</ul>
</cfoutput>
</cfif>
<cfcatch type="any">
<p><strong>✗ Error:</strong> <cfoutput>#cfcatch.message#</cfoutput></p>
</cfcatch>
</cftry>
<hr>
<h2>Example 3: Search with Multiple Criteria</h2>
<cftry>
<cfset searchResult3 = searchCustomers(
firstName="J",
email="example.com"
)>
<p><strong>✓ Search Completed (Multiple Criteria)</strong></p>
<p>Search Criteria: <cfoutput>#arrayToList(searchResult3.searchCriteria, ", ")#</cfoutput></p>
<p>Results Found: <cfoutput>#searchResult3.count#</cfoutput></p>
<cfif searchResult3.count GT 0>
<table border="1" cellpadding="5" cellspacing="0" style="border-collapse: collapse;">
<tr style="background-color: ##f0f0f0;">
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<cfloop array="#searchResult3.results#" index="customer">
<cfoutput>
<tr>
<td>#customer.id#</td>
<td><strong>#customer.firstName#</strong></td>
<td>#customer.lastName#</td>
<td>#customer.email#</td>
<td>#customer.phone#</td>
</tr>
</cfoutput>
</cfloop>
</table>
<cfelse>
<p>No customers found matching the criteria.</p>
</cfif>
<cfcatch type="any">
<p><strong>✗ Error:</strong> <cfoutput>#cfcatch.message#</cfoutput></p>
</cfcatch>
</cftry>
<hr>
<h2>Example 4: Search with Result Limit</h2>
<cftry>
<cfset searchResult4 = searchCustomers(
email="example.com",
maxResults=2
)>
<p><strong>✓ Search Completed (Limited Results)</strong></p>
<p>Search Criteria: <cfoutput>#arrayToList(searchResult4.searchCriteria, ", ")#</cfoutput></p>
<p>Max Results: <cfoutput>#searchResult4.maxResults#</cfoutput></p>
<p>Results Found: <cfoutput>#searchResult4.count#</cfoutput></p>
<cfif searchResult4.count GT 0>
<ul>
<cfloop array="#searchResult4.results#" index="customer">
<cfoutput>
<li>#customer.firstName# #customer.lastName# - #customer.email#</li>
</cfoutput>
</cfloop>
</ul>
<p style="color: ##666;">(Results limited to #searchResult4.maxResults# per search settings)</p>
</cfif>
<cfcatch type="any">
<p><strong>✗ Error:</strong> <cfoutput>#cfcatch.message#</cfoutput></p>
</cfcatch>
</cftry>
<hr>