Whatever message this page gives is out now! Go check it out!

cfargument

Last update:
May 18, 2026

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

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.
  • yes
  • no
restArgSource
Optional
One of the following:
  • path: Extracts parameters from the resource URL. URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the restPath specified in cffunction . The default value cannot be used with path param.
  • query: Extracts parameters from URL query parameters. Mostly used with HTTP GET method. When using GET method to send data, the parameters and values are encoded into the URL. QueryParam is used to extract these values and assign them to the appropriate variables.
  • form: Extracts parameters from a form submission. It is used with HTTP POST method.
  • cookie: Extracts values form a cookie.
  • header: Extracts parameters from HTTP header.
  • matrix: Extracts parameters from matrix URI. For details, see http://www.w3.org/DesignIssues/MatrixURIs.html. If no value is specified, parameters are taken from the body of the request.Using cfhttp , you can send arguments in either form or body. For form parameter, the argument is consumed if you specify form as the value for restArgSource and for body parameter, if you do not specify restArgSource. While calling the service, if you pass the argument in body , in some scenarios, it is accepted as form. For example, <cfhttpparam type="body" value="arg=somevalue">. This is because, when you pass the form name-value pair through cfhttp or the body as "name=value", the body content is same, due to which REST service is not able to detect what is passed. In the service, if you expect body argument but while accessing the service through cfhttp , no argument in the body is passed, you will still receive the body argument as empty string. If you use this attribute, but do not specify the type attribute, string is considered by default as the type.
restArgName
Optional
The name that can be mapped to the argument name.

While calling functions, arguments are extracted from the incoming request. If restArgName is provided, it is searched in the restArgSource scope of the request to populate the argument. If not specified, argument name is searched.

If specified, then argument name has no impact. You can specify correct argument name so that it corresponds to the appropriate parameter. If the argument name passed to a REST service is not a valid Java identifier, for example, the name has hyphen (say arg-name), then you can use this attribute to map the argument name.
type
Optional
any
String; a type name; data type of the argument.
  • any
  • array
  • binary
  • boolean
  • component: the argument must be a ColdFusion component.
  • date
  • email
  • function
  • float
  • guid : the argument must be a UUID or GUID of the form xxxxxxxx - xxxx - xxxx - xxxx - xxxxxxxxxxxx where each_ x_ is a character representing a hexadecimal number (0-9A-F).
  • integer
  • 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 representing a hexadecimal number (0-9A-F).
  • variableName: a string formatted according to ColdFusion variable naming conventions.
  • xml : XML objects and XML strings
  • a component name: if the type 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 argument that is passed in is not a CFC with the specified name.

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>

Share this page

Was this page helpful?
We're glad. Tell us how this page helped.
We're sorry. Can you tell us what didn't work for you?
Thank you for your feedback. Your response will help improve this page.

On this page