- 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
Category
Syntax
<cfif expression> HTML and CFML tags <cfelseif expression> HTML and CFML tags <cfelse> HTML and CFML tags </cfif>
See also
Usage
If the value of the expression in the cfif tag is true, ColdFusion processes all the code that follows, up to any cfelseif or cfelse tag, and then skips to the cfif end tag. Otherwise, ColdFusion does not process the code that immediately follows the cfif tag, and continues processing at any cfelseif or cfelse tag, or with the code that follows the cfif end tag.
When testing the return value of a function that returns a Boolean, you do not have to define the True condition explicitly. This example uses the IsArray function:
<cfif IsArray(myarray)>
If successful, IsArray evaluates to yes, the string equivalent of the Boolean True. This is preferred over explicitly defining the True condition this way:
<cfif IsArray(myarray) IS True>
This tag requires an end tag.
Example
<cfset value = 10>
<cfif value GT 20>
<cfoutput>Greater than 10</cfoutput>
<cfelseif value EQ 8>
<cfoutput>Equal to 8</cfoutput>
<cfelse>
<cfoutput>#value#</cfoutput>
</cfif>
Output
10
Real-world uses of the cfif tag
User access control dashboard
An online store needs to display different pricing information based on customer membership tiers and promotional campaigns, showing discounts and special offers dynamically.
Problem statement
The e-commerce platform has multiple customer tiers (Regular, Silver, Gold, VIP) and needs to calculate and display prices with appropriate discounts. The pricing logic must show original price, discount percentage, and final price based on the customer's membership level. Additionally, bulk order discounts should apply when quantity exceeds certain thresholds.
<cfset productName = "Premium Wireless Headphones">
<cfset basePrice = 199.99>
<cfset quantity = 5>
<cfset customerTier = "Gold"> <!--- Options: Regular, Silver, Gold, VIP --->
<!--- Calculate discount based on customer tier --->
<cfif customerTier EQ "VIP">
<cfset discountPercent = 25>
<cfelseif customerTier EQ "Gold">
<cfset discountPercent = 15>
<cfelseif customerTier EQ "Silver">
<cfset discountPercent = 10>
<cfelse>
<cfset discountPercent = 0>
</cfif>
<!--- Apply bulk order discount --->
<cfif quantity GTE 10>
<cfset bulkDiscount = 5>
<cfelseif quantity GTE 5>
<cfset bulkDiscount = 3>
<cfelse>
<cfset bulkDiscount = 0>
</cfif>
<!--- Calculate total discount and final price --->
<cfset totalDiscount = discountPercent + bulkDiscount>
<cfset discountAmount = basePrice * (totalDiscount / 100)>
<cfset finalPrice = basePrice - discountAmount>
<cfset orderTotal = finalPrice * quantity>
<!--- Display pricing information --->
<cfoutput>
<h2>#productName#</h2>
<p><strong>Base Price:</strong> $#NumberFormat(basePrice, "9.99")#</p>
<p><strong>Quantity:</strong> #quantity#</p>
<p><strong>Customer Tier:</strong> #customerTier#</p>
<cfif totalDiscount GT 0>
<div style="background-color: ##ffe6e6; padding: 10px; margin: 10px 0; border-left: 4px solid ##ff0000;">
<p><strong>Your Savings:</strong></p>
<cfif discountPercent GT 0>
<p>✓ #customerTier# Member Discount: #discountPercent#%</p>
</cfif>
<cfif bulkDiscount GT 0>
<p>✓ Bulk Order Discount: #bulkDiscount#%</p>
</cfif>
<p><strong>Total Discount: #totalDiscount#%</strong></p>
<p><strong>You Save: $#NumberFormat(discountAmount * quantity, "9.99")#</strong></p>
</div>
</cfif>
<p style="font-size: 24px; color: ##006600;">
<strong>Price per Unit: $#NumberFormat(finalPrice, "9.99")#</strong>
</p>
<p style="font-size: 28px; color: ##003399;">
<strong>Order Total: $#NumberFormat(orderTotal, "9.99")#</strong>
</p>
<cfif customerTier EQ "Regular">
<p style="background-color: ##e6f3ff; padding: 10px; border-radius: 5px;">
💡 <em>Upgrade to Silver membership and save 10% on this order!</em>
</p>
</cfif>
</cfoutput>
Form validation and error handling
A customer registration system needs to validate user input in real-time, displaying specific error messages and preventing submission when data doesn't meet business rules.
Problem statement
The registration form collects customer information including email, phone, age, and password. The system must validate that all required fields are present, email format is correct, phone number is valid, user meets minimum age requirement, and password meets complexity requirements. Clear, actionable error messages must guide users to correct their input.
<!--- Simulate form submission --->
<cfparam name="form.submitted" default="true">
<cfparam name="form.email" default="john.doe@example">
<cfparam name="form.phone" default="555-1234">
<cfparam name="form.age" default="16">
<cfparam name="form.password" default="pass123">
<cfparam name="form.confirmPassword" default="pass456">
<cfparam name="form.firstName" default="">
<cfparam name="form.agreeToTerms" default="false">
<cfset errors = ArrayNew(1)>
<cfset isValid = true>
<!--- Perform validation --->
<cfif form.submitted>
<!--- Check First Name --->
<cfif Len(Trim(form.firstName)) EQ 0>
<cfset ArrayAppend(errors, "First Name is required")>
<cfset isValid = false>
</cfif>
<!--- Validate Email --->
<cfif Len(Trim(form.email)) EQ 0>
<cfset ArrayAppend(errors, "Email address is required")>
<cfset isValid = false>
<cfelseif NOT IsValid("email", form.email)>
<cfset ArrayAppend(errors, "Email address format is invalid")>
<cfset isValid = false>
</cfif>
<!--- Validate Phone --->
<cfif Len(Trim(form.phone)) EQ 0>
<cfset ArrayAppend(errors, "Phone number is required")>
<cfset isValid = false>
<cfelseif Len(form.phone) LT 10>
<cfset ArrayAppend(errors, "Phone number must be at least 10 digits")>
<cfset isValid = false>
</cfif>
<!--- Validate Age --->
<cfif NOT IsNumeric(form.age)>
<cfset ArrayAppend(errors, "Age must be a valid number")>
<cfset isValid = false>
<cfelseif form.age LT 18>
<cfset ArrayAppend(errors, "You must be at least 18 years old to register")>
<cfset isValid = false>
<cfelseif form.age GT 120>
<cfset ArrayAppend(errors, "Please enter a valid age")>
<cfset isValid = false>
</cfif>
<!--- Validate Password --->
<cfif Len(form.password) LT 8>
<cfset ArrayAppend(errors, "Password must be at least 8 characters long")>
<cfset isValid = false>
</cfif>
<cfif NOT REFind("[A-Z]", form.password)>
<cfset ArrayAppend(errors, "Password must contain at least one uppercase letter")>
<cfset isValid = false>
</cfif>
<cfif NOT REFind("[0-9]", form.password)>
<cfset ArrayAppend(errors, "Password must contain at least one number")>
<cfset isValid = false>
</cfif>
<!--- Confirm Password Match --->
<cfif form.password NEQ form.confirmPassword>
<cfset ArrayAppend(errors, "Passwords do not match")>
<cfset isValid = false>
</cfif>
<!--- Terms and Conditions --->
<cfif form.agreeToTerms NEQ "true">
<cfset ArrayAppend(errors, "You must agree to the Terms and Conditions")>
<cfset isValid = false>
</cfif>
</cfif>
<!--- Display Results --->
<cfoutput>
<div style="font-family: Arial, sans-serif; max-width: 600px; margin: 20px auto; padding: 20px;">
<h1>Customer Registration Validation</h1>
<cfif form.submitted>
<cfif isValid>
<!--- Success Message --->
<div style="background-color: ##d4edda; border: 1px solid ##c3e6cb; color: ##155724; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
<h2>✓ Registration Successful!</h2>
<p>Welcome aboard! Your account has been created successfully.</p>
<p><strong>Email:</strong> #form.email#</p>
<p><strong>Phone:</strong> #form.phone#</p>
</div>
<cfelse>
<!--- Error Messages --->
<div style="background-color: ##f8d7da; border: 1px solid ##f5c6cb; color: ##721c24; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
<h2>❌ Registration Failed</h2>
<p><strong>Please correct the following errors:</strong></p>
<ul>
<cfloop array="#errors#" index="error">
<li>#error#</li>
</cfloop>
</ul>
</div>
</cfif>
</cfif>
<!--- Display submitted values --->
<div style="background-color: ##f8f9fa; padding: 15px; border-radius: 5px; border: 1px solid ##dee2e6;">
<h3>Submitted Values:</h3>
<table style="width: 100%; border-collapse: collapse;">
<tr>
<td style="padding: 8px; border-bottom: 1px solid ##dee2e6;"><strong>First Name:</strong></td>
<td style="padding: 8px; border-bottom: 1px solid ##dee2e6;">
<cfif Len(Trim(form.firstName)) EQ 0>
<span style="color: red;">(empty)</span>
<cfelse>
#form.firstName#
</cfif>
</td>
</tr>
<tr>
<td style="padding: 8px; border-bottom: 1px solid ##dee2e6;"><strong>Email:</strong></td>
<td style="padding: 8px; border-bottom: 1px solid ##dee2e6;">#form.email#</td>
</tr>
<tr>
<td style="padding: 8px; border-bottom: 1px solid ##dee2e6;"><strong>Phone:</strong></td>
<td style="padding: 8px; border-bottom: 1px solid ##dee2e6;">#form.phone#</td>
</tr>
<tr>
<td style="padding: 8px; border-bottom: 1px solid ##dee2e6;"><strong>Age:</strong></td>
<td style="padding: 8px; border-bottom: 1px solid ##dee2e6;">#form.age#</td>
</tr>
<tr>
<td style="padding: 8px; border-bottom: 1px solid ##dee2e6;"><strong>Password Length:</strong></td>
<td style="padding: 8px; border-bottom: 1px solid ##dee2e6;">#Len(form.password)# characters</td>
</tr>
<tr>
<td style="padding: 8px; border-bottom: 1px solid ##dee2e6;"><strong>Passwords Match:</strong></td>
<td style="padding: 8px; border-bottom: 1px solid ##dee2e6;">
<cfif form.password EQ form.confirmPassword>
<span style="color: green;">✓ Yes</span>
<cfelse>
<span style="color: red;">✗ No</span>
</cfif>
</td>
</tr>
<tr>
<td style="padding: 8px;"><strong>Agreed to Terms:</strong></td>
<td style="padding: 8px;">
<cfif form.agreeToTerms EQ "true">
<span style="color: green;">✓ Yes</span>
<cfelse>
<span style="color: red;">✗ No</span>
</cfif>
</td>
</tr>
</table>
</div>
</div>
</cfoutput>
Service status dashboard with alerts
An IT operations dashboard needs to monitor multiple system services and display color-coded status indicators with appropriate alerts and recommended actions.
Problem statement
The operations team monitors critical services (database, API, email server, storage) with varying response times and uptime percentages. The dashboard must provide at-a-glance status using traffic light colors (green/yellow/red) and display specific alerts when services are degraded or down. Different alert levels require different response protocols.
<!--- Simulate service metrics --->
<cfset services = [
{name="Database Server", responseTime=45, uptime=99.9, status="operational"},
{name="API Gateway", responseTime=250, uptime=98.5, status="degraded"},
{name="Email Server", responseTime=1500, uptime=85.2, status="down"},
{name="Cloud Storage", responseTime=120, uptime=99.99, status="operational"},
{name="Authentication Service", responseTime=180, uptime=97.8, status="degraded"}
]>
<cfset currentTime = Now()>
<cfoutput>
<div style="font-family: Arial, sans-serif; max-width: 900px; margin: 20px auto; padding: 20px; background-color: ##f5f5f5;">
<h1>🖥️ System Status Dashboard</h1>
<p><strong>Last Updated:</strong> #DateFormat(currentTime, "yyyy-mm-dd")# #TimeFormat(currentTime, "HH:mm:ss")#</p>
<hr>
<!--- Overall System Health --->
<cfset criticalCount = 0>
<cfset warningCount = 0>
<cfset okCount = 0>
<cfloop array="#services#" index="service">
<cfif service.status EQ "down">
<cfset criticalCount++>
<cfelseif service.status EQ "degraded">
<cfset warningCount++>
<cfelse>
<cfset okCount++>
</cfif>
</cfloop>
<div style="background-color: white; padding: 20px; margin-bottom: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<h2>System Health Overview</h2>
<cfif criticalCount GT 0>
<div style="background-color: ##dc3545; color: white; padding: 15px; border-radius: 5px; margin-bottom: 10px;">
<h3>🚨 CRITICAL ALERT</h3>
<p><strong>#criticalCount#</strong> service(s) are currently DOWN. Immediate attention required!</p>
</div>
<cfelseif warningCount GT 0>
<div style="background-color: ##ffc107; color: ##000; padding: 15px; border-radius: 5px; margin-bottom: 10px;">
<h3>⚠️ WARNING</h3>
<p><strong>#warningCount#</strong> service(s) are experiencing degraded performance.</p>
</div>
<cfelse>
<div style="background-color: ##28a745; color: white; padding: 15px; border-radius: 5px; margin-bottom: 10px;">
<h3>✓ ALL SYSTEMS OPERATIONAL</h3>
<p>All services are running normally.</p>
</div>
</cfif>
<p><strong>Status Summary:</strong> #okCount# OK | #warningCount# Degraded | #criticalCount# Down</p>
</div>
<!--- Individual Service Status --->
<h2>Service Details</h2>
<cfloop array="#services#" index="service">
<cfset bgColor = "">
<cfset borderColor = "">
<cfset statusIcon = "">
<cfset actionRequired = "">
<!--- Determine status styling and actions --->
<cfif service.status EQ "down">
<cfset bgColor = "##ffe6e6">
<cfset borderColor = "##dc3545">
<cfset statusIcon = "🔴">
<cfset actionRequired = "IMMEDIATE ACTION REQUIRED: Contact on-call engineer">
<cfelseif service.status EQ "degraded">
<cfset bgColor = "##fff9e6">
<cfset borderColor = "##ffc107">
<cfset statusIcon = "🟡">
<cfset actionRequired = "Monitor closely. Consider scaling resources.">
<cfelse>
<cfset bgColor = "##e6ffe6">
<cfset borderColor = "##28a745">
<cfset statusIcon = "🟢">
<cfset actionRequired = "No action needed">
</cfif>
<div style="background-color: #bgColor#; border-left: 5px solid #borderColor#; padding: 15px; margin-bottom: 15px; border-radius: 5px;">
<h3>#statusIcon# #service.name#</h3>
<table style="width: 100%; margin-top: 10px;">
<tr>
<td style="padding: 5px;"><strong>Status:</strong></td>
<td style="padding: 5px;">#UCase(service.status)#</td>
</tr>
<tr>
<td style="padding: 5px;"><strong>Response Time:</strong></td>
<td style="padding: 5px;">
#service.responseTime#ms
<cfif service.responseTime GT 1000>
<span style="color: red; font-weight: bold;"> (SLOW)</span>
<cfelseif service.responseTime GT 200>
<span style="color: orange; font-weight: bold;"> (ELEVATED)</span>
<cfelse>
<span style="color: green;"> (GOOD)</span>
</cfif>
</td>
</tr>
<tr>
<td style="padding: 5px;"><strong>Uptime:</strong></td>
<td style="padding: 5px;">
#NumberFormat(service.uptime, "99.99")#%
<cfif service.uptime LT 95>
<span style="color: red; font-weight: bold;"> (BELOW SLA)</span>
<cfelseif service.uptime LT 99>
<span style="color: orange;"> (WARNING)</span>
<cfelse>
<span style="color: green;"> (EXCELLENT)</span>
</cfif>
</td>
</tr>
<tr>
<td style="padding: 5px;"><strong>Action:</strong></td>
<td style="padding: 5px;">#actionRequired#</td>
</tr>
</table>
<!--- Service-specific recommendations --->
<cfif service.responseTime GT 1000 OR service.uptime LT 95>
<div style="margin-top: 10px; padding: 10px; background-color: rgba(255,255,255,0.7); border-radius: 3px;">
<strong>Recommended Actions:</strong>
<ul style="margin: 5px 0;">
<cfif service.responseTime GT 1000>
<li>Check server load and CPU usage</li>
<li>Review recent configuration changes</li>
<li>Consider scaling resources</li>
</cfif>
<cfif service.uptime LT 95>
<li>Review error logs for patterns</li>
<li>Check network connectivity</li>
<li>Escalate to senior engineers</li>
</cfif>
</ul>
</div>
</cfif>
</div>
</cfloop>
<!--- SLA Compliance Summary --->
<div style="background-color: white; padding: 20px; margin-top: 20px; border-radius: 8px; box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
<h2>SLA Compliance (99% Target)</h2>
<cfloop array="#services#" index="service">
<cfif service.uptime LT 99>
<p style="color: ##dc3545;">
⚠️ <strong>#service.name#</strong> is below SLA target at #NumberFormat(service.uptime, "99.99")#%
</p>
</cfif>
</cfloop>
<cfif criticalCount EQ 0 AND warningCount EQ 0>
<p style="color: ##28a745; font-weight: bold;">✓ All services meeting or exceeding SLA targets</p>
</cfif>
</div>
</div>
</cfoutput>
