Docs | CFWheels

accessibleProperties()

Model Configuration Miscellaneous Functions void model

Use this method to specify which properties can be set through mass assignment.

Name Type Required Default Description
properties string No Property name (or list of property names) that are allowed to be altered through mass assignment.
// Make `isActive` the only property that can be set through mass assignment operations like `updateAll()`.
config() {
	accessibleProperties("isActive");
}

addColumn()

Migrator Migration Functions void migration

adds a column to existing table Only available in a migration CFC

Name Type Required Default Description
table string Yes The Name of the table to add the column to
columnType string Yes The type of the new column
columnName string Yes THe name of the new column
afterColumn string No The name of the column which this column should be inserted after
referenceName string No Name for new reference column, see documentation for references function, required if columnType is 'reference'
default string No Default value for this column
null boolean No Whether to allow NULL values
limit numeric No Character or integer size limit for column
precision numeric No precision value for decimal columns, i.e. number of digits the column can hold
scale numeric No scale value for decimal columns, i.e. number of digits that can be placed to the right of the decimal point (must be less than or equal to precision)
addColumn(table='members', columnType='string', columnName='status', limit=50);

addError()

Model Object Error Functions void model

Adds an error on a specific property.

Name Type Required Default Description
property string Yes The name of the property you want to add an error on.
message string Yes The error message (such as "Please enter a correct name in the form field" for example).
name string No A name to identify the error by (useful when you need to distinguish one error from another one set on the same object and you don't want to use the error message itself for that).
// Add an error to the `email` property.
this.addError(property="email", message="Sorry, you are not allowed to use that email. Try again, please.");

addErrorToBase()

Model Object Error Functions void model

Adds an error on a specific property.

Name Type Required Default Description
message string Yes The error message (such as "Please enter a correct name in the form field" for example).
name string No A name to identify the error by (useful when you need to distinguish one error from another one set on the same object and you don't want to use the error message itself for that).
// Add an error on the object that's not specific to a single property.
this.addErrorToBase(message="Your email address must be the same as your domain name.");

addForeignKey()

Migrator Migration Functions void migration

Add a foreign key constraint to the database, using the reference name that was used to create it Only available in a migration CFC

Name Type Required Default Description
table string Yes The table name to perform the operation on
referenceTable string Yes The reference table name to perform the operation on
column string Yes The column name to perform the operation on
referenceColumn string Yes The reference column name to perform the operation on

addFormat()

Configuration Miscellaneous Functions void controller model migrator migration tabledefinition

Adds a new MIME type to your CFWheels application for use with responding to multiple formats.

Name Type Required Default Description
extension string Yes File extension to add.
mimeType string Yes Matching MIME type to associate with the file extension.
// Add the `js` format
addFormat(extension="js", mimeType="text/javascript");

// Add the `ppt` and `pptx` formats
addFormat(extension="ppt", mimeType="application/vnd.ms-powerpoint");
addFormat(extension="pptx", mimeType="application/vnd.ms-powerpoint");

addIndex()

Migrator Migration Functions void migration

Add database index on a table column Only available in a migration CFC

Name Type Required Default Description
table string Yes The table name to perform the index operation on
columnNames string No One or more column names to index, comma separated
unique boolean No false If true will create a unique index constraint
indexName string No [runtime expression] The name of the index to add: Defaults to table name + underscore + first column name
addIndex(table='members', columnNames='username', unique=true);

addRecord()

Migrator Migration Functions void migration

Adds a record to a table Only available in a migration CFC

Name Type Required Default Description
table string Yes The table name to add the record to
addRecord(table='people',
		id = 1,
		title = "Mr",
		firstname = "Bruce",
		lastname = "Wayne", 
		email = "[email protected]",
		tel = "555-67869099", 
);

addReference()

Migrator Migration Functions void migration

Add a foreign key constraint to the database, using the reference name that was used to create it Only available in a migration CFC

Name Type Required Default Description
table string Yes The table name to perform the operation on
referenceName string Yes The reference table name to perform the operation on

afterCreate()

Model Configuration Callback Functions void model

Registers method(s) that should be called after a new object is created.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method after an object has been created.
afterCreate("fixObj");

afterDelete()

Model Configuration Callback Functions void model

Registers method(s) that should be called after an object is deleted.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method after an object has been deleted.
afterDelete("fixObj");

afterFind()

Model Configuration Callback Functions void model

Registers method(s) that should be called after an existing object has been initialized (which is usually done with the findByKey or findOne method).

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `setTime` method after getting objects or records with one of the finder methods.
config() {
	afterFind("setTime");
}

function setTime(){
	arguments.fetchedAt = Now();
	return arguments;
}

afterInitialization()

Model Configuration Callback Functions void model

Registers method(s) that should be called after an object has been initialized.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method after an object has been initialized (i.e. after creating it or fetching it with a finder method).
afterInitialization("fixObj");

afterNew()

Model Configuration Callback Functions void model

Registers method(s) that should be called after a new object has been initialized (which is usually done with the new method).

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method after a new object has been created.
afterNew("fixObj");

afterSave()

Model Configuration Callback Functions void model

Registers method(s) that should be called after an object is saved.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method after an object has been saved.
afterSave("fixObj");

afterUpdate()

Model Configuration Callback Functions void model

Registers method(s) that should be called after an existing object is updated.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method after an object has been updated.
afterUpdate("fixObj");

afterValidation()

Model Configuration Callback Functions void model

Registers method(s) that should be called after an object is validated.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method after an object has been validated.
afterValidation("fixObj");

afterValidationOnCreate()

Model Configuration Callback Functions void model

Registers method(s) that should be called after a new object is validated.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method after a new object has been validated.
afterValidationOnCreate("fixObj");

afterValidationOnUpdate()

Model Configuration Callback Functions void model

Registers method(s) that should be called after an existing object is validated.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method after an existing object has been validated.
afterValidationOnUpdate("fixObj");

allChanges()

Model Object Change Functions struct model

Returns a struct detailing all changes that have been made on the object but not yet saved to the database.

// Get an object, change it, and then ask for its changes (will return a struct containing the changes, both property names and their values).
member = model("member").findByKey(params.memberId);
member.firstName = params.newFirstName;
member.email = params.newEmail;
allChanges = member.allChanges();

allErrors()

Model Object Error Functions array model

Returns an array of all the errors on the object.

// Get all the errors for the `user` object.
errorInfo = user.allErrors();

// Sample return of method.
[
	{
  	message: 'Username must not be blank.',
    name: 'usernameError',
    property: 'username'
  },
  {
  	message: 'Password must not be blank.',
    name: 'passwordError',
    property: 'password'
  }
]

announce()

any migration tabledefinition

Name Type Required Default Description
message string Yes

authenticityToken()

Controller Miscellaneous Functions string controller

Returns the raw CSRF authenticity token

authenticityTokenField()

View Helpers General Form Functions string controller

Returns a hidden form field containing a new authenticity token.

<!--- Needed here because we're not using `startFormTag`. --->
<form action="#urlFor(route='posts')#" method="post">
  #authenticityTokenField()#
</form>
  
<!--- Not needed here because we're not POSTing the form. --->
<form action="#urlFor(route='invoices')#" method="get">
</form>

automaticValidations()

Model Configuration Validation Functions void model

Whether or not to enable default validations for this model.

Name Type Required Default Description
value boolean Yes Set to true or false.
// Disable automatic validations (for example when automatic validations are enabled globally, but we want to disable just for this model).
config() {
	automaticValidations(false);
}

average()

Model Class Statistics Functions any model

Calculates the average value for a given property. Uses the SQL function AVG. If no records can be found to perform the calculation on you can use the ifNull argument to decide what should be returned.

Name Type Required Default Description
property string Yes Name of the property to calculate the average for.
where string No Maps to the WHERE clause of the query (or HAVING when necessary). The following operators are supported: =, !=, <>, <, <=, >, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, and OR (note that the key words need to be written in upper case). You can also use parentheses to group statements. You do not need to specify the table name(s); CFWheels will do that for you.
include string No Associations that should be included in the query using INNER or LEFT OUTER joins (which join type that is used depends on how the association has been set up in your model). If all included associations are set on the current model, you can specify them in a list (e.g. department,addresses,emails). You can build more complex include strings by using parentheses when the association is set on an included model, like album(artist(genre)), for example. These complex include strings only work when returnAs is set to query though.
distinct boolean No false When true, AVG will be performed only on each unique instance of a value, regardless of how many times the value occurs.
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
ifNull any No The value returned if no records are found. Common usage is to set this to 0 to make sure a numeric value is always returned instead of a blank string.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
group string No Maps to the GROUP BY clause of the query. You do not need to specify the table name(s); CFWheels will do that for you.
// Get the average salary for all employees.
avgSalary = model("employee").average("salary");

// Get the average salary for employees in a given department.
avgSalary = model("employee").average(property="salary", where="departmentId=#params.key#");

// Make sure a numeric value is always returned if no records are calculated.
avgSalary = model("employee").average(property="salary", where="salary BETWEEN #params.min# AND #params.max#", ifNull=0);

beforeCreate()

Model Configuration Callback Functions void model

Registers method(s) that should be called before a new object is created.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method
beforeCreate("fixObj");

beforeDelete()

Model Configuration Callback Functions void model

Registers method(s) that should be called before an object is deleted.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method
beforeDelete("fixObj");

beforeSave()

Model Configuration Callback Functions void model

Registers method(s) that should be called before an object is saved.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method
beforeSave("fixObj");

beforeUpdate()

Model Configuration Callback Functions void model

Registers method(s) that should be called before an existing object is updated.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method
beforeUpdate("fixObj");

beforeValidation()

Model Configuration Callback Functions void model

Registers method(s) that should be called before an object is validated.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method
beforeValidation("fixObj");

beforeValidationOnCreate()

Model Configuration Callback Functions void model

Registers method(s) that should be called before a new object is validated.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method
beforeValidationOnCreate("fixObj");

beforeValidationOnUpdate()

Model Configuration Callback Functions void model

Registers method(s) that should be called before an existing object is validated.

Name Type Required Default Description
methods string No Method name or list of method names that should be called when this callback event occurs in an object's life cycle (can also be called with the method argument).
// Instruct CFWheels to call the `fixObj` method
beforeValidationOnUpdate("fixObj");

belongsTo()

Model Configuration Association Functions void model

Sets up a belongsTo association between this model and the specified one. Use this association when this model contains a foreign key referencing another model.

Name Type Required Default Description
name string Yes Gives the association a name that you refer to when working with the association (in the include argument to findAll, to name one example).
modelName string No Name of associated model (usually not needed if you follow CFWheels conventions because the model name will be deduced from the name argument).
foreignKey string No Foreign key property name (usually not needed if you follow CFWheels conventions since the foreign key name will be deduced from the name argument).
joinKey string No Column name to join to if not the primary key (usually not needed if you follow CFWheels conventions since the join key will be the table's primary key/keys).
joinType string No inner Use to set the join type when joining associated tables. Possible values are inner (for INNER JOIN) and outer (for LEFT OUTER JOIN).
// Specify that instances of this model belong to an author. (The table for this model should have a foreign key set on it, typically named `authorid`.)
belongsTo("author");

// Same as above, but because we have broken away from the foreign key naming convention, we need to set `modelName` and `foreignKey`.
belongsTo(name="bookWriter", modelName="author", foreignKey="authorId");

bigInteger()

Migrator Table Definition Functions any tabledefinition

Adds integer columns to table definition.

Name Type Required Default Description
columnNames string No
limit numeric No
default string No
null boolean No

binary()

Migrator Table Definition Functions any tabledefinition

Adds binary columns to table definition.

Name Type Required Default Description
columnNames string No
default string No
null boolean No

boolean()

Migrator Table Definition Functions any tabledefinition

Adds boolean columns to table definition.

Name Type Required Default Description
columnNames string No
default string No
null boolean No

buttonTag()

View Helpers General Form Functions string controller

Builds and returns a string containing a button form control.

Name Type Required Default Description
content string No Save changes Content to display inside the button.
type string No submit The type for the button: button, reset, or submit.
value string No save The value of the button when submitted.
image string No File name of the image file to use in the button form control.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- View Code --->
#startFormTag(action="something")#
    <!--- Form Controls go here --->
    #buttonTag(content="Submit this form", value="save")#
#endFormTag()#

buttonTo()

View Helpers Link Functions string controller

Creates a form containing a single button that submits to the URL. The URL is built the same way as the linkTo function.

Name Type Required Default Description
text string No The text content of the button.
image string No If you want to use an image for the button pass in the link to it here (relative from the images folder).
route string No Name of a route that you have configured in config/routes.cfm.
controller string No Name of the controller to include in the URL.
action string No Name of the action to include in the URL.
key any No Key(s) to include in the URL.
params string No Any additional parameters to be set in the query string (example: wheels=cool&x=y). Please note that CFWheels uses the & and = characters to split the parameters and encode them properly for you. However, if you need to pass in & or = as part of the value, then you need to encode them (and only them), example: a=cats%26dogs%3Dtrouble!&b=1.
anchor string No Sets an anchor name to be appended to the path.
method string No The type of method to use in the form tag (delete, get, patch, post, and put are the options).
onlyPath boolean No true If true, returns only the relative URL (no protocol, host name or port).
host string No Set this to override the current host.
protocol string No Set this to override the current protocol.
port numeric No 0 Set this to override the current port number.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
#buttonTo(text="Delete Account", action="perFormDelete", disable="Wait...")#

<!--- apply attributes to the input element by prefixing any arguments with "input"--->
#buttonTo(text="Edit", action="edit", inputId="edit-button", inputClass="edit-button-class")#

caches()

Controller Configuration Functions void controller

Tells CFWheels to cache one or more actions.

Name Type Required Default Description
action string No Action(s) to cache. This argument is also aliased as actions.
time numeric No 60 Minutes to cache the action(s) for.
static boolean No false Set to true to tell CFWheels that this is a static page and that it can skip running the controller filters (before and after filters set on actions). Please note that the onSessionStart and onRequestStart events still execute though.
appendToKey string No List of variables to be evaluated at runtime and included in the cache key so that content can be cached separately.
// Cache the `termsOfUse` action.
caches("termsOfUse");

// Cache the `termsOfUse` action for 30 minutes.
caches(actions="browseByUser, browseByTitle", time=30);

// Cache the `termsOfUse` and `codeOfConduct` actions, including their filters.
caches(actions="termsOfUse, codeOfConduct", static=true);

// Cache content separately based on region.
caches(action="home", key="request.region");

capitalize()

Global Helpers String Functions string controller model mapper migrator migration tabledefinition

Capitalizes all words in the text to create a nicer looking title.

Name Type Required Default Description
text string Yes
<!--- Capitalize a sentence, will result in "Wheels is a framework"--->
#capitalize("wheels is a framework")#

change()

Migrator Table Definition Functions void tabledefinition

alters existing table in the database

Name Type Required Default Description
addColumns boolean No false

changeColumn()

Migrator Migration Functions void migration

changes a column definition Only available in a migration CFC

Name Type Required Default Description
table string Yes The Name of the table where the column is
columnName string Yes THe name of the column
columnType string Yes The type of the column
afterColumn string No The name of the column which this column should be inserted after
referenceName string No Name for reference column, see documentation for references function, required if columnType is 'reference'
default string No Default value for this column
null boolean No Whether to allow NULL values
limit numeric No Character or integer size limit for column
precision numeric No (For decimal type) the maximum number of digits allow
scale numeric No (For decimal type) the number of digits to the right of the decimal point
addColumns boolean No false if true, attempts to add columns and database will likely throw an error if column already exists
changeColumn(table='members', columnType='string', columnName='status', limit=50);

changedFrom()

Model Object Change Functions string model

Returns the previous value of a property that has changed. Returns an empty string if no previous value exists. CFWheels will keep a note of the previous property value until the object is saved to the database.

Name Type Required Default Description
property string Yes Name of property to get the previous value for.
// Get a member object and change the `email` property on it
member = model("member").findByKey(params.memberId);
member.email = params.newEmail;

// Get the previous value (what the `email` property was before it was changed)
oldValue = member.changedFrom("email");

// The above can also be done using a dynamic function like this
oldValue = member.emailChangedFrom();

changedProperties()

Model Object Change Functions string model

Returns a list of the object properties that have been changed but not yet saved to the database.

// Get an object, change it, and then ask for its changes (will return a list of the property names that have changed, not the values themselves)
member = model("member").findByKey(params.memberId);
member.firstName = params.newFirstName;
member.email = params.newEmail;
changedProperties = member.changedProperties();

changeTable()

Migrator Migration Functions TableDefinition migration

Creates a table definition object to store modifications to table properties Only available in a migration CFC

Name Type Required Default Description
name string Yes Name of the table to set change properties on
t = changeTable(name='employees');
t.string(columnNames="fullName", default="", null=true, limit="255");
t.change();

char()

Migrator Table Definition Functions any tabledefinition

adds char columns to table definition

Name Type Required Default Description
columnNames string No
limit any No
default string No
null boolean No

checkBox()

View Helpers Form Object Functions string controller

Builds and returns a string containing a check box form control based on the supplied name. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
objectName any Yes The variable name of the object to build the form control for.
property string Yes The name of the property to use in the form control.
association string No The name of the association that the property is located on. Used for building nested forms that work with nested properties. If you are building a form with deep nesting, simply pass in a list to the nested object, and CFWheels will figure it out.
position string No The position used when referencing a hasMany relationship in the association argument. Used for building nested forms that work with nested properties. If you are building a form with deep nestings, simply pass in a list of positions, and CFWheels will figure it out.
checkedValue string No 1
uncheckedValue string No 0 The value of the check box when it's on the unchecked state.
label string No useDefaultLabel The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
errorElement string No span HTML tag to wrap the form control with when the object contains errors.
errorClass string No field-with-errors The class name of the HTML tag that wraps the form control when there are errors.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- Basic example of a check box for a boolean field --->
#checkBox(objectName="photo", property="isPublic", label="Display this photo publicly.")#

<!--- Shows check boxes for selecting public access for all photos provided by the `photos` association and nested properties --->
<cfloop from="1" to="#ArrayLen(user.photos)#" index="i">
    <div>
        <h3>#user.photos[i].title#:</h3>
        <div>
            #checkBox(objectName="user", association="photos", position=i, property="isPublic", label="Display this photo publicly.")#
        </div>
    </div>
</cfloop>

checkBoxTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing a check box form control based on the supplied name. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
checked boolean No false Whether or not the check box should be checked by default.
value string No 1 Value of check box in its checked state.
uncheckedValue string No The value of the check box when it's on the unchecked state.
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- Example 1: Basic usage involves a `label`, `name`, and `value` --->
#checkBoxTag(name="subscribe", value="true", label="Subscribe to our newsletter", checked=false)#

<!--- Example 2: Loop over a query to display choices and whether or not they are checked --->
// Controller code
pizza = model("pizza").findByKey(session.pizzaId);
selectedToppings = pizza.toppings();
toppings = model("topping").findAll(order="name");

<!--- View code --->
<fieldset>
	<legend>Toppings</legend>
	<cfoutput query="toppings">
		#checkBoxTag(name="toppings", value="true", label=toppings.name, checked=YesNoFormat(ListFind(ValueList(selectedToppings.id), toppings.id))#
	</cfoutput>
</fieldset>

clearChangeInformation()

Model Object Change Functions void model

Clears all internal knowledge of the current state of the object.

Name Type Required Default Description
property string No string false Name of property to clear information for.
// Convert startTime to UTC (maybe done in an "after find" call back) but then tell CFWheels to clear the information about this change (but not the change itself) so that it won't attempt to save the new value to the database, report it as being changed when calling hasChanged() etc.

this.startTime = DateConvert("Local2UTC", this.startTime);
this.clearChangeInformation(property="startTime");

// Clear information for all properties
this.clearChangeInformation();

clearErrors()

Model Object Error Functions void model

Clears out all errors set on the object or only the ones set for a specific property or name.

Name Type Required Default Description
property string No Specify a property name here if you want to clear all errors set on that property.
name string No Specify an error name here if you want to clear all errors set with that error name.
// Clear all errors on the object as a whole
this.clearErrors();

// Clear all errors on `firstName`
this.clearErrors("firstName");

collection()

Configuration Routing struct mapper

A collection route doesn't require an id because it acts on a collection of objects. photos/search is an example of a collection route, because it acts on (and displays) a collection of objects.


<cfscript>

mapper()
    // Create a route like `photos/search`
    .resources(name="photos", nested=true)
        .collection()
            .get("search")
        .end()
    .end()
.end();

</cfscript>

column()

Migrator Table Definition Functions any tabledefinition

Adds a column to table definition.

Name Type Required Default Description
columnName string Yes
columnType string Yes
default string No
null boolean No
limit any No
precision numeric No
scale numeric No

columnDataForProperty()

Model Class Miscellaneous Functions any model

Returns a struct with data for the named property.

Name Type Required Default Description
property string Yes Name of property to inspect.

columnForProperty()

Model Class Miscellaneous Functions any model

Returns the column name mapped for the named model property.

Name Type Required Default Description
property string Yes Name of property to inspect.

columnNames()

Model Class Miscellaneous Functions string model

Returns a list of column names in the table mapped to this model. The list is ordered according to the columns' ordinal positions in the database table.

columns()

Model Class Miscellaneous Functions array model

Returns an array of columns names for the table associated with this class. Does not include calculated properties that will be generated by the CFWheels ORM.

compareTo()

Model Object Miscellaneous Functions boolean model

Pass in another model object to see if the two objects are the same.

Name Type Required Default Description
object component Yes

constraints()

Configuration Routing struct mapper

Set variable patterns to use for matching.

contentFor()

View Helpers Miscellaneous Functions void controller

Used to store a section's output for rendering within a layout. This content store acts as a stack, so you can store multiple pieces of content for a given section.

Name Type Required Default Description
position any No last The position in the section's stack where you want the content placed. Valid values are first, last, or the numeric position.
overwrite any No false Whether or not to overwrite any of the content. Valid values are false, true, or all.
<!--- In your view --->
<cfsavecontent variable="mySidebar">
<h1>My Sidebar Text</h1>
</cfsavecontent>
<cfset contentFor(sidebar=mySidebar)>

<!--- In your layout --->
<html>
	<head>
	    <title>My Site</title>
	</head>
	<body>
		<cfoutput>
			#includeContent("sidebar")#
			#includeContent()#
		</cfoutput>
	</body>
</html>

contentForLayout()

View Helpers Miscellaneous Functions string controller

Includes content for the body section, which equates to the output generated by the view template run by the request.

<!--- In `views/layout.cfm` --->
#contentForLayout()#

controller()

Configuration Routing struct mapper

Considered deprecated as this doesn't conform to RESTful routing principles; Try not to use this.

Name Type Required Default Description
controller string Yes
name string No [runtime expression]
path string No [runtime expression]

controller()

Global Helpers Miscellaneous Functions any controller model migrator migration tabledefinition

Creates and returns a controller object with your own custom name and params. Used primarily for testing purposes.

Name Type Required Default Description
name string Yes Name of the controller to create.
params struct No [runtime expression] The params struct (combination of form and URL variables).
testController = controller("users", params);

count()

Model Class Statistics Functions any model

Returns the number of rows that match the arguments (or all rows if no arguments are passed in). Uses the SQL function COUNT. If no records can be found to perform the calculation on, 0 is returned.

Name Type Required Default Description
where string No Maps to the WHERE clause of the query (or HAVING when necessary). The following operators are supported: =, !=, <>, <, <=, >, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, and OR (note that the key words need to be written in upper case). You can also use parentheses to group statements. You do not need to specify the table name(s); CFWheels will do that for you.
include string No Associations that should be included in the query using INNER or LEFT OUTER joins (which join type that is used depends on how the association has been set up in your model). If all included associations are set on the current model, you can specify them in a list (e.g. department,addresses,emails). You can build more complex include strings by using parentheses when the association is set on an included model, like album(artist(genre)), for example. These complex include strings only work when returnAs is set to query though.
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
group string No Maps to the GROUP BY clause of the query. You do not need to specify the table name(s); CFWheels will do that for you.
// Count how many authors there are in the table
authorCount = model("author").count();

// Count how many authors that have a last name starting with an "A"
authorOnACount = model("author").count(where="lastName LIKE 'A%'");

// Count how many authors that have written books starting with an "A"
authorWithBooksOnACount = model("author").count(include="books", where="booktitle LIKE 'A%'");

// Count the number of comments on a specific post (a `hasMany` association from `post` to `comment` is required)
// The `commentCount` method will call `model("comment").count(where="postId=#post.id#")` internally
aPost = model("post").findByKey(params.postId);
amount = aPost.commentCount();

create()

Migrator Table Definition Functions void tabledefinition

creates the table in the database

create()

Model Class Create Functions any model

Creates a new object, saves it to the database (if the validation permits it), and returns it. If the validation fails, the unsaved object (with errors added to it) is still returned. Property names and values can be passed in either using named arguments or as a struct to the properties argument.

Name Type Required Default Description
properties struct No [runtime expression] The properties you want to set on the object (can also be passed in as named arguments).
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
reload boolean No false Set to true to force CFWheels to query the database even though an identical query for this model may have been run in the same request. (The default in CFWheels is to get the second query from the model's request-level cache.)
validate boolean No true Set to false to skip validations for this operation.
transaction string No [runtime expression] Set this to commit to update the database, rollback to run all the database queries but not commit them, or none to skip transaction handling altogether.
callbacks boolean No true Set to false to disable callbacks for this method.
allowExplicitTimestamps boolean No false Set this to true to allow explicit assignment of createdAt or updatedAt properties
// Create a new author and save it to the database
newAuthor = model("author").create(params.author);

// Same as above using named arguments
newAuthor = model("author").create(firstName="John", lastName="Doe");

// Same as above using both named arguments and a struct
newAuthor = model("author").create(active=1, properties=params.author);

// If you have a `hasOne` or `hasMany` association setup from `customer` to `order`, you can do a scoped call. (The `createOrder` method below will call `model("order").create(customerId=aCustomer.id, shipping=params.shipping)` internally.)
aCustomer = model("customer").findByKey(params.customerId);
anOrder = aCustomer.createOrder(shipping=params.shipping);

createMigration()

Migrator General Functions string migrator

Creates a migration file. Whilst you can use this in your application, the recommended useage is via either the CLI or the provided GUI interface

Name Type Required Default Description
migrationName string Yes
templateName string No
migrationPrefix string No timestamp
// Create an empty migration file
result=application.wheels.migrator.createMigration("MyMigrationFile");

// Or Create a migration file from the create-table template
result=application.wheels.migrator.createMigration("MyMigrationFile","create-table");

createTable()

Migrator Migration Functions TableDefinition migration

Creates a table definition object to store table properties Only available in a migration CFC

Name Type Required Default Description
name string Yes The name of the table to create
force boolean No false whether to drop the table before creating it
id boolean No true Whether to create a default primarykey or not
primaryKey string No id Name of the primary key field to create
// Example: create a users table
t = createTable(name='users'); 
	t.string(columnNames='firstname,lastname', default='', null=false, limit=50);
	t.string(columnNames='email', default='', null=false, limit=255); 
	t.string(columnNames='passwordHash', default='', null=true, limit=500);
	t.string(columnNames='passwordResetToken,verificationToken', default='', null=true, limit=500);
	t.boolean(columnNames='passwordChangeRequired,verified', default=false); 
	t.datetime(columnNames='passwordResetTokenAt,passwordResetAt,loggedinAt', default='', null=true); 
	t.integer(columnNames='roleid', default=0, null=false, limit=3);
	t.timestamps();
t.create();

// Example: Create a table with a different Primary Key
t = createTable(name='tokens', id=false);
	t.primaryKey(name='id', null=false, type="string", limit=35 );
	t.datetime(columnNames="expiresAt", null=false);
	t.integer(columnNames='requests', default=0, null=false);
	t.timestamps();
t.create();

// Example: Create a Join Table with composite primary keys
t = createTable(name='userkintins', id=false); 
	t.primaryKey(name="userid", null=false, limit=11);
	t.primaryKey(name='profileid', type="string", limit=11 );  
t.create();

createView()

Migrator Migration Functions ViewDefinition migration

Creates a view definition object to store view properties Only available in a migration CFC

Name Type Required Default Description
name string Yes Name of the view to change properties on

csrfMetaTags()

View Helpers Miscellaneous Functions string controller

Include this in your layouts' head sections to include meta tags containing the authenticity token for use by JavaScript AJAX requests needing to POST data to your application.

Name Type Required Default Description
encode boolean No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<head>
  #csrfMetaTags()#
</head>

cycle()

View Helpers Miscellaneous Functions string controller

Cycles through list values every time it is called.

Name Type Required Default Description
values string Yes List of values to cycle through.
name string No default Name to give the cycle. Useful when you use multiple cycles on a page.
<!--- Alternating table row colors --->
<table>
	<thead>
		<tr>
			<th>Name</th>
			<th>Phone</th>
		</tr>
	</thead>
	<tbody>
		<cfoutput query="employees">
			<tr class="#cycle("odd,even")#">
				<td>#employees.name#</td>
				<td>#employees.phone#</td>
			</tr>
		</cfoutput>
	</tbody>
</table>

<!--- Alternating row colors and shrinking emphasis --->
<cfoutput query="employees" group="departmentId">
	<div class="#cycle(values="even,odd", name="row")#">
		<ul>
			<cfoutput>
				rank = cycle(values="president,vice-president,director,manager,specialist,intern", name="position")>
				<li class="#rank#">#categories.categoryName#</li>
				resetCycle("emphasis")>
			</cfoutput>
		</ul>
	</div>
</cfoutput>

dataSource()

Model Configuration Miscellaneous Functions void model

Use this method to override the data source connection information for this model.

Name Type Required Default Description
datasource string Yes The data source name to connect to.
username string No The username for the data source.
password string No The password for the data source.
// In models/User.cfc.
config() {
	// Tell Wheels to use the data source named `users_source` instead of the default one whenever this model makes SQL calls.
	dataSource("users_source");
}

date()

Migrator Table Definition Functions any tabledefinition

Adds date columns to table definition.

Name Type Required Default Description
columnNames string No
default string No
null boolean No

dateSelect()

View Helpers Form Object Functions string controller

Builds and returns a string containing three select form controls for month, day, and year based on the supplied objectName and property.

Name Type Required Default Description
objectName any No The variable name of the object to build the form control for.
property string No The name of the property to use in the form control.
association string No The name of the association that the property is located on. Used for building nested forms that work with nested properties. If you are building a form with deep nesting, simply pass in a list to the nested object, and CFWheels will figure it out.
position string No The position used when referencing a hasMany relationship in the association argument. Used for building nested forms that work with nested properties. If you are building a form with deep nestings, simply pass in a list of positions, and CFWheels will figure it out.
order string No month,day,year Use to change the order of or exclude date select tags.
separator string No
startYear numeric No 2019 First year in select list.
endYear numeric No 2029 Last year in select list.
monthDisplay string No names Pass in names, numbers, or abbreviations to control display.
monthNames string No January,February,March,April,May,June,July,August,September,October,November,December
monthAbbreviations string No Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
label string No false The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
errorElement string No span HTML tag to wrap the form control with when the object contains errors.
errorClass string No field-with-errors The class name of the HTML tag that wraps the form control when there are errors.
combine boolean No Set to false to not combine the select parts into a single DateTime object.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- View code --->
#dateSelect(objectName="user", property="dateOfBirth")#

<!--- Show fields to select month and year --->
#dateSelect(objectName="order", property="expirationDate", order="month,year")#

dateSelectTags()

View Helpers Form Tag Functions string controller

Builds and returns a string containing three select form controls (month, day, and year) based on a name and value.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
selected string No Value of option that should be selected by default.
order string No month,day,year Use to change the order of or exclude date select tags.
separator string No [see:dateSelect].
startYear numeric No 2019 First year in select list.
endYear numeric No 2029 Last year in select list.
monthDisplay string No names Pass in names, numbers, or abbreviations to control display.
monthNames string No January,February,March,April,May,June,July,August,September,October,November,December [see:dateSelect].
monthAbbreviations string No Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec [see:dateSelect].
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
combine boolean No Set to false to not combine the select parts into a single DateTime object.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- This "Tag" version of function accepts `name` and `selected` instead of binding to a model object --->
#dateSelectTags(name="dateStart", selected=params.dateStart)#

<!--- Show fields for month and year only --->
#dateSelectTags(name="expiration", selected=params.expiration, order="month,year")#

datetime()

Migrator Table Definition Functions any tabledefinition

adds datetime columns to table definition

Name Type Required Default Description
columnNames string No
default string No
null boolean No

dateTimeSelect()

View Helpers Form Object Functions string controller

Builds and returns a string containing six select form controls (three for date selection and the remaining three for time selection) based on the supplied objectName and property.

Name Type Required Default Description
objectName string Yes The variable name of the object to build the form control for.
property string Yes The name of the property to use in the form control.
association string No The name of the association that the property is located on. Used for building nested forms that work with nested properties. If you are building a form with deep nesting, simply pass in a list to the nested object, and Wheels will figure it out.
position string No The position used when referencing a hasMany relationship in the association argument. Used for building nested forms that work with nested properties. If you are building a form with deep nestings, simply pass in a list of positions, and Wheels will figure it out.
dateOrder string No month,day,year Use to change the order of or exclude date select tags.
dateSeparator string No
startYear numeric No 2019 Last year in select list.
endYear numeric No 2029
monthDisplay string No names Pass in names, numbers, or abbreviations to control display.
monthNames string No January,February,March,April,May,June,July,August,September,October,November,December
monthAbbreviations string No Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec
timeOrder string No hour,minute,second Use to change the order of or exclude time select tags.
timeSeparator string No : Use to change the character that is displayed between the time select tags.
minuteStep numeric No 1 Pass in 10 to only show minute 10, 20, 30, etc.
secondStep numeric No 1 Pass in 10 to only show seconds 10, 20, 30, etc
separator string No - Use to change the character that is displayed between the first and second set of select tags.
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
label string No false The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
errorElement string No span HTML tag to wrap the form control with when the object contains errors.
errorClass string No field-with-errors The class name of the HTML tag that wraps the form control when there are errors.
combine boolean No Set to false to not combine the select parts into a single DateTime object.
twelveHour boolean No false Whether to display the hours in 24 or 12 hour format. 12 hour format has AM/PM drop downs
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- View code --->
#dateTimeSelect(objectName="article", property="publishedAt")#

<!--- Show fields for month, day, hour, and minute --->
#dateTimeSelect(objectName="appointment", property="dateTimeStart", dateOrder="month,day", timeOrder="hour,minute")#

dateTimeSelectTags()

View Helpers Form Tag Functions string controller

Builds and returns a string containing six select form controls (three for date selection and the remaining three for time selection) based on a name.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
selected string No Value of option that should be selected by default.
dateOrder string No month,day,year Use to change the order of or exclude date select tags.
dateSeparator string No [see:dateTimeSelect].
startYear numeric No 2019 First year in select list.
endYear numeric No 2029 Last year in select list.
monthDisplay string No names Pass in names, numbers, or abbreviations to control display.
monthNames string No January,February,March,April,May,June,July,August,September,October,November,December [see:dateSelect].
monthAbbreviations string No Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec [see:dateSelect].
timeOrder string No hour,minute,second Use to change the order of or exclude time select tags.
timeSeparator string No : Use to change the character that is displayed between the time select tags.
minuteStep numeric No 1 Pass in 10 to only show minute 10, 20, 30, etc.
secondStep numeric No 1 Pass in 10 to only show seconds 10, 20, 30, etc.
separator string No - Use to change the character that is displayed between the first and second set of select tags.
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
combine boolean No Set to false to not combine the select parts into a single DateTime object.
twelveHour boolean No false whether to display the hours in 24 or 12 hour format. 12 hour format has AM/PM drop downs
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- This "Tag" version of the function accepts a `name` and `selected` instead of binding to a model object--->
#dateTimeSelectTags(name="dateTimeStart", selected=params.dateTimeStart)#

<!--- Show fields for month, day, hour, and minute--->
#dateTimeSelectTags(name="dateTimeStart", selected=params.dateTimeStart, dateOrder="month,day", timeOrder="hour,minute")#

daySelectTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing a select form control for the days of the week based on the supplied name.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
selected string No The day that should be selected initially.
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- This "Tag" version of the function accepts a `name` and `selected` instead of binding to a model object --->
#daySelectTag(name="dayOfWeek", selected=params.dayOfWeek)#

decimal()

Migrator Table Definition Functions any tabledefinition

adds decimal columns to table definition

Name Type Required Default Description
columnNames string No
default string No
null boolean No
precision numeric No
scale numeric No

delete()

Configuration Routing struct mapper

Create a route that matches a URL requiring an HTTP DELETE method. We recommend using this matcher to expose actions that delete database records.

Name Type Required Default Description
name string No Camel-case name of route to reference when build links and form actions (e.g., blogPost).
pattern string No Overrides the URL pattern that will match the route. The default value is a dasherized version of name (e.g., a name of blogPost generates a pattern of blog-post).
to string No Set controller##action combination to map the route to. You may use either this argument or a combination of controller and action.
controller string No Map the route to a given controller. This must be passed along with the action argument.
action string No Map the route to a given action within the controller. This must be passed along with the controller argument.
package string No Indicates a subfolder that the controller will be referenced from (but not added to the URL pattern). For example, if you set this to admin, the controller will be located at admin/YourController.cfc, but the URL path will not contain admin/.
on string No If this route is within a nested resource, you can set this argument to member or collection. A member route contains a reference to the resource's key, while a collection route does not.
redirect string No Redirect via 302 to this URL when this route is matched. Has precedence over controller/action. Use either an absolute link like /about/, or a full canonical link.
<cfscript>

mapper()
    // Route name:  articleReview
    // Example URL: /articles/987/reviews/12542
    // Controller:  Reviews
    // Action:      delete
    .delete(name="articleReview", pattern="articles/[articleKey]/reviews/[key]", to="reviews##delete")

    // Route name:  cookedBooks
    // Example URL: /cooked-books
    // Controller:  CookedBooks
    // Action:      delete
    .delete(name="cookedBooks", controller="cookedBooks", action="delete")

    // Route name:  logout
    // Example URL: /logout
    // Controller:  Sessions
    // Action:      delete
    .delete(name="logout", to="sessions##delete")

    // Route name:  clientsStatus
    // Example URL: /statuses/4918
    // Controller:  clients.Statuses
    // Action:      delete
    .delete(name="statuses", to="statuses##delete", package="clients")

    // Route name:  blogComment
    // Example URL: /comments/5432
    // Controller:  blog.Comments
    // Action:      delete
    .delete(
        name="comment",
        pattern="comments/[key]",
        to="comments##delete",
        package="blog"
    )
.end();

</cfscript>

delete()

Model Object CRUD Functions boolean model

Deletes the object, which means the row is deleted from the database (unless prevented by a beforeDelete callback). Returns true on successful deletion of the row, false otherwise.

Name Type Required Default Description
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
transaction string No [runtime expression] Set this to commit to update the database, rollback to run all the database queries but not commit them, or none to skip transaction handling altogether.
callbacks boolean No true Set to false to disable callbacks for this method.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
softDelete boolean No true Set to false to permanently delete a record, even if it has a soft delete column.
// Get a post object and then delete it from the database.
post = model("post").findByKey(33);
post.delete();

// If you have a `hasMany` association setup from `post` to `comment`, you can do a scoped call. (The `deleteComment` method below will call `comment.delete()` internally.)
post = model("post").findByKey(params.postId);
comment = model("comment").findByKey(params.commentId);
post.deleteComment(comment);

deleteAll()

Model Class Delete Functions numeric model

Deletes all records that match the where argument. By default, objects will not be instantiated and therefore callbacks and validations are not invoked. You can change this behavior by passing in instantiate=true. Returns the number of records that were deleted.

Name Type Required Default Description
where string No Maps to the WHERE clause of the query (or HAVING when necessary). The following operators are supported: =, !=, <>, <, <=, >, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, and OR (note that the key words need to be written in upper case). You can also use parentheses to group statements. You do not need to specify the table name(s); CFWheels will do that for you.
include string No Associations that should be included in the query using INNER or LEFT OUTER joins (which join type that is used depends on how the association has been set up in your model). If all included associations are set on the current model, you can specify them in a list (e.g. department,addresses,emails). You can build more complex include strings by using parentheses when the association is set on an included model, like album(artist(genre)), for example. These complex include strings only work when returnAs is set to query though.
reload boolean No false Set to true to force CFWheels to query the database even though an identical query for this model may have been run in the same request. (The default in CFWheels is to get the second query from the model's request-level cache.)
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
instantiate boolean No false Whether or not to instantiate the object(s) first. When objects are not instantiated, any callbacks and validations set on them will be skipped.
transaction string No [runtime expression] Set this to commit to update the database, rollback to run all the database queries but not commit them, or none to skip transaction handling altogether.
callbacks boolean No true Set to false to disable callbacks for this method.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
softDelete boolean No true Set to false to permanently delete a record, even if it has a soft delete column.
// Delete all inactive users without instantiating them (will skip validation and callbacks).
recordsDeleted = model("user").deleteAll(where="inactive=1", instantiate=false);

// If you have a `hasMany` association setup from `post` to `comment`, you can do a scoped call. (The `deleteAllComments` method below will call `model("comment").deleteAll(where="postId=#post.id#")` internally.)
post = model("post").findByKey(params.postId);
howManyDeleted = post.deleteAllComments();

deleteByKey()

Model Class Delete Functions boolean model

Finds the record with the supplied key and deletes it. Returns true on successful deletion of the row, false otherwise.

Name Type Required Default Description
key any Yes Primary key value(s) of the record to fetch. Separate with comma if passing in multiple primary key values. Accepts a string, list, or a numeric value.
reload boolean No false Set to true to force CFWheels to query the database even though an identical query for this model may have been run in the same request. (The default in CFWheels is to get the second query from the model's request-level cache.)
transaction string No [runtime expression] Set this to commit to update the database, rollback to run all the database queries but not commit them, or none to skip transaction handling altogether.
callbacks boolean No true Set to false to disable callbacks for this method.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
softDelete boolean No true Set to false to permanently delete a record, even if it has a soft delete column.
// Delete the user with the primary key value of `1`.
result = model("user").deleteByKey(1);

deleteOne()

Model Class Delete Functions boolean model

Gets an object based on conditions and deletes it.

Name Type Required Default Description
where string No Maps to the WHERE clause of the query (or HAVING when necessary). The following operators are supported: =, !=, <>, <, <=, >, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, and OR (note that the key words need to be written in upper case). You can also use parentheses to group statements. You do not need to specify the table name(s); CFWheels will do that for you.
order string No Maps to the ORDER BY clause of the query. You do not need to specify the table name(s); CFWheels will do that for you.
reload boolean No false Set to true to force CFWheels to query the database even though an identical query for this model may have been run in the same request. (The default in CFWheels is to get the second query from the model's request-level cache.)
transaction string No [runtime expression] Set this to commit to update the database, rollback to run all the database queries but not commit them, or none to skip transaction handling altogether.
callbacks boolean No true Set to false to disable callbacks for this method.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
softDelete boolean No true Set to false to permanently delete a record, even if it has a soft delete column.
// Delete the user that signed up last.
result = model("user").deleteOne(order="signupDate DESC");

// If you have a `hasOne` association setup from `user` to `profile` you can do a scoped call (the `deleteProfile` method below will call `model("profile").deleteOne(where="userId=#aUser.id#")` internally).
aUser = model("user").findByKey(params.userId);
aUser.deleteProfile();

deobfuscateParam()

Global Helpers Miscellaneous Functions string controller model migrator migration tabledefinition

Deobfuscates a value.

Name Type Required Default Description
param string Yes The value to deobfuscate.
// Get the original value from an obfuscated one
originalValue = deobfuscateParam("b7ab9a50");

distanceOfTimeInWords()

Global Helpers Date Functions string controller model migrator migration tabledefinition

Pass in two dates to this method, and it will return a string describing the difference between them.

Name Type Required Default Description
fromTime date Yes Date to compare from.
toTime date Yes Date to compare to.
includeSeconds boolean No false Whether or not to include the number of seconds in the returned string.
// Controller code.
rightNow = Now();
aWhileAgo = DateAdd("d", -30, rightNow);

// View code.
<!--- Will output: about 1 month --->
#distanceOfTimeInWords(aWhileAgo, rightNow)#

down()

Migrator Migration Functions void migration

Migrates down: will be executed when migrating your schema backward Along with up(), these are the two main functions in any migration file Only available in a migration CFC

function down() {
	transaction {
		try {
			// your code goes here
			dropTable('myTable');
		} catch (any e) {
			local.exception = e;
		}

		if (StructKeyExists(local, "exception")) {
			transaction action="rollback";
			throw(errorCode="1", detail=local.exception.detail, message=local.exception.message, type="any");
		} else {
			transaction action="commit";
		}
	}
}

dropForeignKey()

Migrator Migration Functions void migration

Drops a foreign key constraint from the database Only available in a migration CFC

Name Type Required Default Description
table string Yes The table name to perform the operation on
keyName string Yes the name of the key to drop

dropReference()

Migrator Migration Functions void migration

Drop a foreign key constraint from the database, using the reference name that was used to create it Only available in a migration CFC

Name Type Required Default Description
table string Yes The table name to perform the operation on
referenceName string Yes the name of the reference to drop

dropTable()

Migrator Migration Functions void migration

Drops a table from the database Only available in a migration CFC

Name Type Required Default Description
name string Yes Name of the table to drop

dropView()

Migrator Migration Functions void migration

drops a view from the database Only available in a migration CFC

Name Type Required Default Description
name string Yes Name of the view to drop

end()

Configuration Routing struct mapper

Call this to end a nested routing block or the entire route configuration. This method is chained on a sequence of routing mapper method calls started by mapper().

<cfscript>

mapper()
    .namespace("admin")
        .resources("products")
    .end() // Ends the `namespace` block.

    .scope(package="public")
        .resources(name="products", nested=true)
          .resources("variations")
        .end() // Ends the nested `resources` block.
    .end() // Ends the `scope` block.
.end(); // Ends the `mapper` block.

</cfscript>

endFormTag()

View Helpers General Form Functions string controller

Builds and returns a string containing the closing form tag.

Name Type Required Default Description
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- view code --->
#startFormTag(action="create")#
   <!---  your form controls --->
#endFormTag()#

errorCount()

Model Object Error Functions numeric model

Returns the number of errors this object has associated with it. Specify property or name if you wish to count only specific errors.

Name Type Required Default Description
property string No Specify a property name here if you want to count only errors set on a specific property.
name string No Specify an error name here if you want to count only errors set with a specific error name.
// Check how many errors are set on the object
if(author.errorCount() GTE 10){
    // Do something to deal with this very erroneous author here...
}

// Check how many errors are associated with the `email` property
if(author.errorCount("email") gt 0){
    // Do something to deal with this erroneous author here...
}

errorMessageOn()

View Helpers Error Functions string controller

Returns the error message, if one exists, on the object's property. If multiple error messages exist, the first one is returned.

Name Type Required Default Description
objectName string Yes The variable name of the object to display the error message for.
property string Yes The name of the property to display the error message for.
prependText string No String to prepend to the error message.
appendText string No String to append to the error message.
wrapperElement string No span HTML element to wrap the error message in.
class string No error-message CSS class to set on the wrapper element.
encode boolean No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.

errorMessagesFor()

View Helpers Error Functions string controller

Builds and returns a list (ul tag with a default class of error-messages) containing all the error messages for all the properties of the object. Returns an empty string if no errors exist.

Name Type Required Default Description
objectName string Yes The variable name of the object to display error messages for.
class string No error-messages CSS class to set on the ul element.
showDuplicates boolean No true Whether or not to show duplicate error messages.
encode boolean No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.

errorsOn()

Model Object Error Functions array model

Returns an array of all errors associated with the supplied property (and error name if passed in).

Name Type Required Default Description
property string Yes Specify the property name to return errors for here.
name string No If you want to return only errors on the property set with a specific error name you can specify it here.
// Get all errors related to the email address of the user object
errors = user.errorsOn("emailAddress");

errorsOnBase()

Model Object Error Functions array model

Returns an array of all errors associated with the object as a whole (not related to any specific property).

Name Type Required Default Description
name string No Specify an error name here to only return errors for that error name.
// Get all general type errors for the user object
errors = user.errorsOnBase();

excerpt()

Global Helpers String Functions string controller model migrator migration tabledefinition

Extracts an excerpt from text that matches the first instance of a given phrase.

Name Type Required Default Description
text string Yes The text to extract an excerpt from.
phrase string Yes The phrase to extract.
radius numeric No 100 Number of characters to extract surrounding the phrase.
excerptString string No ... String to replace first and / or last characters with.
<!--- Will output: ... MVC framework for ... --->
#excerpt(text="CFWheels is a Rails-like MVC framework for Adobe ColdFusion and Lucee", phrase="framework", radius=5)#

execute()

Migrator Migration Functions void migration

Executes a raw sql query Only available in a migration CFC

Name Type Required Default Description
sql string Yes Arbitary SQL String

exists()

Model Class Miscellaneous Functions boolean model

Checks if a record exists in the table. You can pass in either a primary key value to the key argument or a string to the where argument. If you don't pass in either of those, it will simply check if any record exists in the table.

Name Type Required Default Description
key any No Primary key value(s) of the record. Separate with comma if passing in multiple primary key values. Accepts a string, list, or a numeric value.
where string No Maps to the WHERE clause of the query (or HAVING when necessary). The following operators are supported: =, !=, <>, <, <=, >, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, and OR (note that the key words need to be written in upper case). You can also use parentheses to group statements. You do not need to specify the table name(s); CFWheels will do that for you.
reload boolean No false Set to true to force CFWheels to query the database even though an identical query for this model may have been run in the same request. (The default in CFWheels is to get the second query from the model's request-level cache.)
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
includeSoftDeletes boolean No Set to true to include soft-deleted records in the queries that this method runs.
// Checking if Joe exists in the database
result = model("user").exists(where="firstName = 'Joe'");

// Checking if a specific user exists based on a primary key valued passed in through the URL/form in an if statement
if (model("user").exists(keyparams.key))
{
	// Do something
}

// If you have a `belongsTo` association setup from `comment` to `post`, you can do a scoped call. (The `hasPost` method below will call `model("post").exists(comment.postId)` internally.)
comment = model("comment").findByKey(params.commentId);
commentHasAPost = comment.hasPost();

// If you have a `hasOne` association setup from `user` to `profile`, you can do a scoped call. (The `hasProfile` method below will call `model("profile").exists(where="userId=#user.id#")` internally.)
user = model("user").findByKey(params.userId);
userHasProfile = user.hasProfile();

// If you have a `hasMany` association setup from `post` to `comment`, you can do a scoped call. (The `hasComments` method below will call `model("comment").exists(where="postid=#post.id#")` internally.)
post = model("post").findByKey(params.postId);
postHasComments = post.hasComments();

fileField()

View Helpers Form Object Functions string controller

Builds and returns a string containing a file field form control based on the supplied objectName and property. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
objectName any Yes The variable name of the object to build the form control for.
property string Yes The name of the property to use in the form control.
association string No The name of the association that the property is located on. Used for building nested forms that work with nested properties. If you are building a form with deep nesting, simply pass in a list to the nested object, and CFWheels will figure it out.
position string No The position used when referencing a hasMany relationship in the association argument. Used for building nested forms that work with nested properties. If you are building a form with deep nestings, simply pass in a list of positions, and CFWheels will figure it out.
label string No useDefaultLabel The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
errorElement string No span HTML tag to wrap the form control with when the object contains errors.
errorClass string No field-with-errors The class name of the HTML tag that wraps the form control when there are errors.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- Provide a `label` and the required `objectName` and `property` --->
#fileField(label="Photo", objectName="photo", property="imageFile")#


<!--- Display fields for photos provided by the `screenshots` association and nested properties --->
<fieldset>
	<legend>Screenshots</legend>
	<cfloop from="1" to="#ArrayLen(site.screenshots)#" index="i">
		#fileField(label="File ##i#", objectName="site", association="screenshots", position=i, property="file")#
		#textField(label="Caption ##i#", objectName="site", association="screenshots", position=i, property="caption")#
	</cfloop>
</fieldset>

fileFieldTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing a file form control based on the supplied name. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!---  Basic usage usually involves a `label`, `name`, and `value` --->
#fileFieldTag(label="Photo", name="photo", value=params.photo)#

filterChain()

Controller Configuration Functions array controller

Returns an array of all the filters set on current controller in the order in which they will be executed.

Name Type Required Default Description
type string No all Use this argument to return only before or after filters.
// Get filter chain.
myFilterChain = filterChain();

// Get filter chain for after filters only.
myFilterChain = filterChain(type="after");

filters()

Controller Configuration Functions void controller

Tells CFWheels to run a function before an action is run or after an action has been run.

Name Type Required Default Description
through string Yes Function(s) to execute before or after the action(s).
type string No before Whether to run the function(s) before or after the action(s).
only string No Pass in a list of action names (or one action name) to tell CFWheels that the filter function(s) should only be run on these actions.
except string No Pass in a list of action names (or one action name) to tell CFWheels that the filter function(s) should be run on all actions except the specified ones.
placement string No append Pass in prepend to prepend the function(s) to the filter chain instead of appending.
// Always execute `restrictAccess` before all actions in this controller.
filters("restrictAccess");

// Always execute `isLoggedIn` and `checkIPAddress` (in that order) before all actions in this controller, except the `home` and `login` actions.
filters(through="isLoggedIn, checkIPAddress", except="home, login");

findAll()

Model Class Read Functions any model

Returns records from the database table mapped to this model according to the arguments passed in (use the where argument to decide which records to get, use the order argument to set the order in which those records should be returned, and so on). The records will be returned as either a cfquery result set, an array of objects, or an array of structs (depending on what the returnAs argument is set to).

Name Type Required Default Description
where string No Maps to the WHERE clause of the query (or HAVING when necessary). The following operators are supported: =, !=, <>, <, <=, >, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, and OR (note that the key words need to be written in upper case). You can also use parentheses to group statements. You do not need to specify the table name(s); CFWheels will do that for you.
order string No Maps to the ORDER BY clause of the query. You do not need to specify the table name(s); CFWheels will do that for you.
group string No Maps to the GROUP BY clause of the query. You do not need to specify the table name(s); CFWheels will do that for you.
select string No Determines how the SELECT clause for the query used to return data will look. You can pass in a list of the properties (which map to columns) that you want returned from your table(s). If you don't set this argument at all, CFWheels will select all properties from your table(s). If you specify a table name (e.g. users.email) or alias a column (e.g. fn AS firstName) in the list, then the entire list will be passed through unchanged and used in the SELECT clause of the query. By default, all column names in tables joined via the include argument will be prepended with the singular version of the included table name.
distinct boolean No false Whether to add the DISTINCT keyword to your SELECT clause. CFWheels will, when necessary, add this automatically (when using pagination and a hasMany association is used in the include argument, to name one example).
include string No Associations that should be included in the query using INNER or LEFT OUTER joins (which join type that is used depends on how the association has been set up in your model). If all included associations are set on the current model, you can specify them in a list (e.g. department,addresses,emails). You can build more complex include strings by using parentheses when the association is set on an included model, like album(artist(genre)), for example. These complex include strings only work when returnAs is set to query though.
maxRows numeric No -1 Maximum number of records to retrieve. Passed on to the maxRows cfquery attribute. The default, -1, means that all records will be retrieved.
page numeric No 0 If you want to paginate records, you can do so by specifying a page number here. For example, getting records 11-20 would be page number 2 when perPage is kept at the default setting (10 records per page). The default, 0, means that records won't be paginated and that the perPage and count arguments will be ignored.
perPage numeric No 10 When using pagination, you can specify how many records you want to fetch per page here. This argument is only used when the page argument has been passed in.
count numeric No 0 When using pagination and you know in advance how many records you want to paginate through, you can pass in that value here. Doing so will prevent CFWheels from running a COUNT query to get this value. This argument is only used when the page argument has been passed in.
handle string No query Handle to use for the query. This is used when you're paginating multiple queries and need to reference them individually in the paginationLinks() function. It's also used to set the name of the query in the debug output (which otherwise defaults to userFindAllQuery for example).
cache any No If you want to cache the query, you can do so by specifying the number of minutes you want to cache the query for here. If you set it to true, the default cache time will be used (60 minutes).
reload boolean No false Set to true to force CFWheels to query the database even though an identical query for this model may have been run in the same request. (The default in CFWheels is to get the second query from the model's request-level cache.)
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
returnAs string No query Set to objects to return an array of objects, set to structs to return an array of structs, or set to query to return a query result set.
returnIncluded boolean No true When returnAs is set to objects, you can set this argument to false to prevent returning objects fetched from associations specified in the include argument. This is useful when you only need to include associations for use in the WHERE clause only and want to avoid the performance hit that comes with object creation.
callbacks boolean No true Set to false to disable callbacks for this method.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
useIndex struct No [runtime expression] If you want to specify table index hints, pass in a structure of index names using your model names as the structure keys. Eg: {user="idx_users", post="idx_posts"}. This feature is only supported by MySQL and SQL Server.
// Getting only 5 users and ordering them randomly
fiveRandomUsers = model("user").findAll(maxRows=5, order="random");

// Including an association (which in this case needs to be setup as a `belongsTo` association to `author` on the `article` model first)
articles = model("article").findAll( include="author", where="published=1", order="createdAt DESC" );

// Similar to the above but using the association in the opposite direction (which needs to be setup as a `hasMany` association to `article` on the `author` model)  bobsArticles = model("author").findAll( include="articles", where="firstName='Bob'" );

// Using pagination (getting records 26-50 in this case) and a more complex way to include associations (a song `belongsTo` an album, which in turn `belongsTo` an artist)  songs = model("song").findAll( include="album(artist)", page=2, perPage=25 );

// Using a dynamic finder to get all books released a certain year. Same as calling model("book").findOne(where="releaseYear=#params.year#")
books = model("book").findAllByReleaseYear(params.year);

// Getting all books of a certain type from a specific year by using a dynamic finder. Same as calling  model("book").findAll( where="releaseYear=#params.year# AND type='#params.type#'" )
books = model("book").findAllByReleaseYearAndType( "#params.year#,#params.type#" );

// If you have a `hasMany` association setup from `post` to `comment`, you can do a scoped call. (The `comments` method below will call `model("comment").findAll(where="postId=#post.id#")` internally)
post = model("post").findByKey(params.postId);
comments = post.comments();

// If you have an `Order` model with properties for `productId`, `amount` and a calculated property named `totalAmount` (set up as `property(name="totalAmount", sql="SUM(amount)")`), then you can do the following to get the ids for all products with over $1,000 in sales (the SQL will be created using `HAVING` instead of `WHERE` in this case since you're getting an aggregate value for a calculated property)
ids = model("order").findAll(group="productId", where="totalAmount > 1000");

// Using index hints
indexes = {
	author="idx_authors_123",
	post="idx_posts_123"
}
posts = model("author").findAll(where="firstname LIKE '#params.q#%' OR subject LIKE '#params.q#%'", include="posts", useIndex=indexes);

findAllKeys()

Model Class Read Functions string model

Returns all primary key values in a list. In addition to quoted and delimiter you can pass in any argument that findAll() accepts.

Name Type Required Default Description
quoted boolean No false Set to true to enclose each value in single-quotation marks.
delimiter string No , The delimiter character to separate the list items with.
// basic usage
primaryKeyList = model("artist").findAllKeys();

// Quote values, use a different delimiter and filter results with the "where" argument
primaryKeyList = model("artist").findAllKeys(quoted=true, delimiter="-", where="active=1");

findByKey()

Model Class Read Functions any model

Fetches the requested record by primary key and returns it as an object. Returns false if no record is found. You can override this behavior to return a cfquery result set instead, similar to what's described in the documentation for findOne().

Name Type Required Default Description
key any Yes Primary key value(s) of the record. Separate with comma if passing in multiple primary key values. Accepts a string, list, or a numeric value.
select string No Determines how the SELECT clause for the query used to return data will look. You can pass in a list of the properties (which map to columns) that you want returned from your table(s). If you don't set this argument at all, CFWheels will select all properties from your table(s). If you specify a table name (e.g. users.email) or alias a column (e.g. fn AS firstName) in the list, then the entire list will be passed through unchanged and used in the SELECT clause of the query. By default, all column names in tables joined via the include argument will be prepended with the singular version of the included table name.
include string No Associations that should be included in the query using INNER or LEFT OUTER joins (which join type that is used depends on how the association has been set up in your model). If all included associations are set on the current model, you can specify them in a list (e.g. department,addresses,emails). You can build more complex include strings by using parentheses when the association is set on an included model, like album(artist(genre)), for example. These complex include strings only work when returnAs is set to query though.
handle string No query Handle to use for the query. This is used to set the name of the query in the debug output (which otherwise defaults to userFindOneQuery for example).
cache any No If you want to cache the query, you can do so by specifying the number of minutes you want to cache the query for here. If you set it to true, the default cache time will be used (60 minutes).
reload boolean No false Set to true to force CFWheels to query the database even though an identical query for this model may have been run in the same request. (The default in CFWheels is to get the second query from the model's request-level cache.)
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
returnAs string No object Set to objects to return an array of objects, set to structs to return an array of structs, or set to query to return a query result set.
callbacks boolean No true Set to false to disable callbacks for this method.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
// Getting the author with the primary key value `99` as an object
auth = model("author").findByKey(99);

// Getting an author based on a form/URL value and then checking if it was found
auth = model("author").findByKey(params.key);
if(!isObject(auth)){
    flashInsert(message="Author #params.key# was not found");
    redirectTo(back=true);
}

// If you have a `belongsTo` association setup from `comment` to `post`, you can do a scoped call. (The `post` method below will call `model("post").findByKey(comment.postId)` internally)
comment = model("comment").findByKey(params.commentId);
post = comment.post();

findFirst()

Model Class Read Functions any model

Fetches the first record ordered by primary key value. Use the property argument to order by something else. Returns a model object.

Name Type Required Default Description
property string No [runtime expression] Name of the property to order by. This argument is also aliased as properties.

findLastOne()

Model Class Read Functions any model

Fetches the last record ordered by primary key value. Use the property argument to order by something else. Returns a model object. Formerly known as findLast.

Name Type Required Default Description
property string No Name of the property to order by. This argument is also aliased as properties.

findOne()

Model Class Read Functions any model

Fetches the first record found based on the WHERE and ORDER BY clauses. With the default settings (i.e. the returnAs argument set to object), a model object will be returned if the record is found and the boolean value false if not. Instead of using the where argument, you can create cleaner code by making use of a concept called Dynamic Finders.

Name Type Required Default Description
where string No Maps to the WHERE clause of the query (or HAVING when necessary). The following operators are supported: =, !=, <>, <, <=, >, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, and OR (note that the key words need to be written in upper case). You can also use parentheses to group statements. You do not need to specify the table name(s); CFWheels will do that for you.
order string No Maps to the ORDER BY clause of the query. You do not need to specify the table name(s); CFWheels will do that for you.
select string No Determines how the SELECT clause for the query used to return data will look. You can pass in a list of the properties (which map to columns) that you want returned from your table(s). If you don't set this argument at all, CFWheels will select all properties from your table(s). If you specify a table name (e.g. users.email) or alias a column (e.g. fn AS firstName) in the list, then the entire list will be passed through unchanged and used in the SELECT clause of the query. By default, all column names in tables joined via the include argument will be prepended with the singular version of the included table name.
include string No Associations that should be included in the query using INNER or LEFT OUTER joins (which join type that is used depends on how the association has been set up in your model). If all included associations are set on the current model, you can specify them in a list (e.g. department,addresses,emails). You can build more complex include strings by using parentheses when the association is set on an included model, like album(artist(genre)), for example. These complex include strings only work when returnAs is set to query though.
handle string No query Handle to use for the query. This is used to set the name of the query in the debug output (which otherwise defaults to userFindOneQuery for example).
cache any No If you want to cache the query, you can do so by specifying the number of minutes you want to cache the query for here. If you set it to true, the default cache time will be used (60 minutes).
reload boolean No false Set to true to force CFWheels to query the database even though an identical query for this model may have been run in the same request. (The default in CFWheels is to get the second query from the model's request-level cache.)
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
returnAs string No object Set to objects to return an array of objects, set to structs to return an array of structs, or set to query to return a query result set.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
useIndex struct No [runtime expression] If you want to specify table index hints, pass in a structure of index names using your model names as the structure keys. Eg: {user="idx_users", post="idx_posts"}. This feature is only supported by MySQL and SQL Server.
// Getting the most recent order as an object from the database
order = model("order").findOne(order="datePurchased DESC");

// Using a dynamic finder to get the first person with the last name `Smith`. Same as calling `model("user").findOne(where"lastName='Smith'")`
person = model("user").findOneByLastName("Smith");

// Getting a specific user using a dynamic finder. Same as calling `model("user").findOne(where"email='[email protected]' AND password='mypass'")`
user = model("user").findOneByEmailAndPassword("[email protected],mypass");

// If you have a `hasOne` association setup from `user` to `profile`, you can do a scoped call. (The `profile` method below will call `model("profile").findOne(where="userId=#user.id#")` internally)
user = model("user").findByKey(params.userId);
profile = user.profile();

// If you have a `hasMany` association setup from `post` to `comment`, you can do a scoped call. (The `findOneComment` method below will call `model("comment").findOne(where="postId=#post.id#")` internally)
post = model("post").findByKey(params.postId);
comment = post.findOneComment(where="text='I Love Wheels!'");

flash()

Controller Flash Functions any controller

Returns the value of a specific key in the Flash (or the entire Flash as a struct if no key is passed in).

Name Type Required Default Description
key string No The key to get the value for.
// Get the current value of notice in the Flash
notice = flash("notice");

// Get the entire Flash as a struct
flashContents = flash();

flashClear()

Controller Flash Functions void controller

Deletes everything from the Flash.

flashClear();

flashCount()

Controller Flash Functions numeric controller

Returns how many keys exist in the Flash.

count = flashCount();

flashDelete()

Controller Flash Functions any controller

Deletes a specific key from the Flash. Returns true if the key exists.

Name Type Required Default Description
key string Yes The key to delete
flashDelete(key="errorMessage");

flashInsert()

Controller Flash Functions void controller

Inserts a new key / value into the Flash.

flashInsert(msg="It Worked!");

flashIsEmpty()

Controller Flash Functions boolean controller

Returns whether or not the Flash is empty.

empty = flashIsEmpty();

flashKeep()

Controller Flash Functions void controller

Make the entire Flash or specific key in it stick around for one more request.

Name Type Required Default Description
key string No
// Keep the entire Flash for the next request
flashKeep();

// Keep the "error" key in the Flash for the next request
flashKeep("error");

// Keep both the "error" and "success" keys in the Flash for the next request
flashKeep("error,success");

flashKeyExists()

Controller Flash Functions boolean controller

Checks if a specific key exists in the Flash.

Name Type Required Default Description
key string Yes The key to check.
errorExists = flashKeyExists("error");

flashMessages()

View Helpers Miscellaneous Functions string controller

Displays a marked-up listing of messages that exist in the Flash.

Name Type Required Default Description
keys string No The key (or list of keys) to show the value for. You can also use the key argument instead for better readability when accessing a single key.
class string No flash-messages HTML class to set on the div element that contains the messages.
includeEmptyContainer boolean No false Includes the div container even if the Flash is empty.
encode boolean No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
// In the controller action
flashInsert(success="Your post was successfully submitted.");
flashInsert(alert="Don't forget to tweet about this post!");
flashInsert(error="This is an error message.");

<!--- In the layout or view --->
#flashMessages()#

<!--- Generates this (sorted alphabetically):--->
<div class="flashMessages">
	<p class="alertMessage">
		Don't forget to tweet about this post!
	</p>
	<p class="errorMessage">
		This is an error message.
	</p>
	<p class="successMessage">
		Your post was successfully submitted.
	</p>
</div>


<!---  Only show the "success" key in the view --->
#flashMessages(key="success")#

<!--- Generates this: --->
<div class="flashMessage">
	<p class="successMessage">
		Your post was successfully submitted.
	</p>
</div>


<!--- Show only the "success" and "alert" keys in the view, in that order --->
#flashMessages(keys="success,alert")#

<!--- Generates this (sorted alphabetically):--->
<div class="flashMessages">
	<p class="successMessage">
		Your post was successfully submitted.
	</p>
	<p class="alertMessage">
		Don't forget to tweet about this post!
	</p>
</div>

float()

Migrator Table Definition Functions any tabledefinition

adds float columns to table definition

Name Type Required Default Description
columnNames string No
default string No
null boolean No true

get()

Configuration Routing struct mapper

Create a route that matches a URL requiring an HTTP GET method. We recommend only using this matcher to expose actions that display data. See post, patch, delete, and put for matchers that are appropriate for actions that change data in your database.

Name Type Required Default Description
name string No Camel-case name of route to reference when build links and form actions (e.g., blogPost).
pattern string No Overrides the URL pattern that will match the route. The default value is a dasherized version of name (e.g., a name of blogPost generates a pattern of blog-post).
to string No Set controller##action combination to map the route to. You may use either this argument or a combination of controller and action.
controller string No Map the route to a given controller. This must be passed along with the action argument.
action string No Map the route to a given action within the controller. This must be passed along with the controller argument.
package string No Indicates a subfolder that the controller will be referenced from (but not added to the URL pattern). For example, if you set this to admin, the controller will be located at admin/YourController.cfc, but the URL path will not contain admin/.
on string No If this route is within a nested resource, you can set this argument to member or collection. A member route contains a reference to the resource's key, while a collection route does not.
redirect string No Redirect via 302 to this URL when this route is matched. Has precedence over controller/action. Use either an absolute link like /about/, or a full canonical link.
<cfscript>

mapper()
    // Route name:  post
    // Example URL: /posts/my-post-title
    // Controller:  Posts
    // Action:      show
    .get(name="post", pattern="posts/[slug]", to="posts##show")

    // Route name:  posts
    // Example URL: /posts
    // Controller:  Posts
    // Action:      index
    .get(name="posts", controller="posts", action="index")

    // Route name:  authors
    // Example URL: /the-scribes
    // Controller:  Authors
    // Action:      index
    .get(name="authors", pattern="the-scribes", to="authors##index")

    // Route name:  commerceCart
    // Example URL: /cart
    // Controller:  commerce.Carts
    // Action:      show
    .get(name="cart", to="carts##show", package="commerce")

    // Route name:  extranetEditProfile
    // Example URL: /profile/edit
    // Controller:  extranet.Profiles
    // Action:      edit
    .get(
        name="editProfile",
        pattern="profile/edit",
        to="profiles##edit",
        package="extranet"
    )

    // Example scoping within a nested resource
    .resources(name="users", nested=true)
        // Route name:  activatedUsers
        // Example URL: /users/activated
        // Controller:  Users
        // Action:      activated
        .get(name="activated", to="users##activated", on="collection")

        // Route name:  preferencesUsers
        // Example URL: /users/391/preferences
        // Controller:  Preferences
        // Action:      index
        .get(name="preferences", to="preferences##index", on="member")
    .end()
.end();

</cfscript>

get()

Configuration Miscellaneous Functions any controller model migrator migration tabledefinition

Returns the current setting for the supplied CFWheels setting or the current default for the supplied CFWheels function argument.

Name Type Required Default Description
name string Yes Variable name to get setting for.
functionName string No Function name to get setting for.
// Get the current value for the `tableNamePrefix` Wheels setting
setting = get("tableNamePrefix");

// Get the default for the `message` argument of the `validatesConfirmationOf` method
setting = get(functionName="validatesConfirmationOf", name="message");

getAvailableMigrations()

Migrator General Functions array migrator

Searches db/migrate folder for migrations. Whilst you can use this in your application, the recommended useage is via either the CLI or the provided GUI interface

Name Type Required Default Description
path string No [runtime expression] Path to Migration Files: defaults to /migrator/migrations/
// Get array of available migrations
migrations = application.wheels.migrator.getAvailableMigrations();

if(ArrayLen(migrations)){
	 latestVersion = migrations[ArrayLen(migrations)].version;
} else {
	 latestVersion = 0;
}

getCurrentMigrationVersion()

Migrator General Functions string migrator

Returns current database version. Whilst you can use this in your application, the recommended useage is via either the CLI or the provided GUI interface

// Get current database version
currentVersion = application.wheels.migrator.getCurrentMigrationVersion();

getEmails()

Controller Miscellaneous Functions array controller

Primarily used for testing to get information about emails sent during the request.

getFiles()

Controller Miscellaneous Functions array controller

Primarily used for testing to get information about files sent during the request.

getRedirect()

Controller Miscellaneous Functions struct controller

Primarily used for testing to establish whether the current request has performed a redirect.

getTableNamePrefix()

Model Class Miscellaneous Functions string model

Returns the table name prefix set for the table.

// Get the table name prefix for this user when running a custom query.
<cffunction name="getDisabledUsers" returntype="query">
	<cfquery datasource="#get('dataSourceName')#" name="local.disabledUsers">
	SELECT *
	FROM #this.getTableNamePrefix()#users
	WHERE disabled = 1
	</cfquery>
	<cfreturn local.disabledUsers>
</cffunction>

hasChanged()

Model Object Change Functions boolean model

Returns true if the specified property (or any if none was passed in) has been changed but not yet saved to the database. Will also return true if the object is new and no record for it exists in the database.

Name Type Required Default Description
property string No Name of property to check for change.
// Get a member object and change the `email` property on it
member = model("member").findByKey(params.memberId);
member.email = params.newEmail;

// Check if the `email` property has changed
if(member.hasChanged("email")){
    // Do something...
}

// The above can also be done using a dynamic function like this
if(member.emailHasChanged()){
    // Do something...
}

hasErrors()

Model Object Error Functions boolean model

Returns true if the object has any errors. You can also limit to only check a specific property or name for errors.

Name Type Required Default Description
property string No Name of the property to check if there are any errors set on.
name string No Error name to check if there are any errors set with.
// Check if the post object has any errors set on it 
if(post.hasErrors()){
    // Send user to a form to correct the errors... 
}

hasMany()

Model Configuration Association Functions void model

Sets up a hasMany association between this model and the specified one.

Name Type Required Default Description
name string Yes Gives the association a name that you refer to when working with the association (in the include argument to findAll, to name one example).
modelName string No Name of associated model (usually not needed if you follow CFWheels conventions because the model name will be deduced from the name argument).
foreignKey string No Foreign key property name (usually not needed if you follow CFWheels conventions since the foreign key name will be deduced from the name argument).
joinKey string No Column name to join to if not the primary key (usually not needed if you follow CFWheels conventions since the join key will be the table's primary key/keys).
joinType string No outer Use to set the join type when joining associated tables. Possible values are inner (for INNER JOIN) and outer (for LEFT OUTER JOIN).
dependent string No false Defines how to handle dependent model objects when you delete an object from this model. delete / deleteAll deletes the record(s) (deleteAll bypasses object instantiation). remove / removeAll sets the forein key field(s) to NULL (removeAll bypasses object instantiation).
shortcut string No Set this argument to create an additional dynamic method that gets the object(s) from the other side of a many-to-many association.
through string No [runtime expression] Set this argument if you need to override CFWheels conventions when using the shortcut argument. Accepts a list of two association names representing the chain from the opposite side of the many-to-many relationship to this model.
// Specify that instances of this model has many comments (the table for the associated model, not the current, should have the foreign key set on it).
hasMany("comments");

// Specify that this model (let's call it `reader` in this case) has many subscriptions and setup a shortcut to the `publication` model (useful when dealing with many-to-many relationships).
hasMany(name="subscriptions", shortcut="publications");

// Automatically delete all associated `comments` whenever this object is deleted.
hasMany(name="comments", dependent="deleteAll");

// When not following CFWheels naming conventions for associations, it can get complex to define how a `shortcut` works.
// In this example, we are naming our `shortcut` differently than the actual model's name.

// In the models/Customer.cfc `config()` method.
hasMany(name="subscriptions", shortcut="magazines", through="publication,subscriptions");

// In the models/Subscription.cfc `config()` method.
belongsTo("customer");
belongsTo("publication");

// In the models/Publication `config()` method.
hasMany("subscriptions");

hasManyCheckBox()

View Helpers Form Association Functions string controller

Used as a shortcut to output the proper form elements for an association. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
objectName string Yes Name of the variable containing the parent object to represent with this form field.
association string Yes Name of the association set in the parent object to represent with this form field.
keys string Yes Primary keys associated with this form field. Note that these keys should be listed in the order that they appear in the database table.
label string No The label text to use in the form control.
labelPlacement string No Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
errorElement string No HTML tag to wrap the form control with when the object contains errors.
errorClass string No The class name of the HTML tag that wraps the form control when there are errors.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- Show check boxes for associating authors with the current book --->
<cfloop query="authors">
    #hasManyCheckBox(
        label=authors.fullName,
        objectName="book",
        association="bookAuthors",
        keys="#book.key()#,#authors.id#"
    )#
</cfloop>

hasManyRadioButton()

View Helpers Form Association Functions string controller

Used as a shortcut to output the proper form elements for an association. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
objectName string Yes Name of the variable containing the parent object to represent with this form field.
association string Yes Name of the association set in the parent object to represent with this form field.
property string Yes Name of the property in the child object to represent with this form field.
keys string Yes Primary keys associated with this form field. Note that these keys should be listed in the order that they appear in the database table.
tagValue string Yes The value of the radio button when selected.
checkIfBlank boolean No false Whether or not to check this form field as a default if there is a blank value set for the property.
label string No The label text to use in the form control.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- Show radio buttons for associating a default address with the current author --->
<cfloop query="addresses">
    #hasManyRadioButton(
        label=addresses.title,
        objectName="author",
        association="authorsDefaultAddresses",
        keys="#author.key()#,#addresses.id#"
    )#
</cfloop>

hasOne()

Model Configuration Association Functions void model

Sets up a hasOne association between this model and the specified one.

Name Type Required Default Description
name string Yes Gives the association a name that you refer to when working with the association (in the include argument to findAll, to name one example).
modelName string No Name of associated model (usually not needed if you follow CFWheels conventions because the model name will be deduced from the name argument).
foreignKey string No Foreign key property name (usually not needed if you follow CFWheels conventions since the foreign key name will be deduced from the name argument).
joinKey string No Column name to join to if not the primary key (usually not needed if you follow CFWheels conventions since the join key will be the table's primary key/keys).
joinType string No outer Use to set the join type when joining associated tables. Possible values are inner (for INNER JOIN) and outer (for LEFT OUTER JOIN).
dependent string No false Defines how to handle dependent model objects when you delete an object from this model. delete / deleteAll deletes the record(s) (deleteAll bypasses object instantiation). remove / removeAll sets the forein key field(s) to NULL (removeAll bypasses object instantiation).
// Specify that instances of this model has one profile. (The table for the associated model, not the current, should have the foreign key set on it.)
hasOne("profile");

// Same as above but setting the `joinType` to `inner`, which basically means this model should always have a record in the `profiles` table.
hasOne(name="profile", joinType="inner");

// Automatically delete the associated `profile` whenever this object is deleted.
hasMany(name="comments", dependent="delete");

hasProperty()

Model Object Miscellaneous Functions boolean model

Returns true if the specified property name exists on the model.

Name Type Required Default Description
property string Yes Name of property to inspect.
// Get an object, set a value and then see if the property exists
employee = model("employee").new();
employee.firstName = "dude";
employee.hasProperty("firstName"); // returns true

// This is also a dynamic method that you could do
employee.hasFirstName();

hiddenField()

View Helpers Form Object Functions string controller

Builds and returns a string containing a hidden field form control based on the supplied objectName and property. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
objectName any Yes The variable name of the object to build the form control for.
property string Yes The name of the property to use in the form control.
association string No The name of the association that the property is located on. Used for building nested forms that work with nested properties. If you are building a form with deep nesting, simply pass in a list to the nested object, and CFWheels will figure it out.
position string No The position used when referencing a hasMany relationship in the association argument. Used for building nested forms that work with nested properties. If you are building a form with deep nestings, simply pass in a list of positions, and CFWheels will figure it out.
encode boolean No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- Provide an `objectName` and `property` --->
#hiddenField(objectName="user", property="id")#

hiddenFieldTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing a hidden field form control based on the supplied name. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
value string No Value to populate in tag's value attribute.
encode boolean No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- Basic usage usually involves a `name` and `value` --->
#hiddenFieldTag(name="userId", value=user.id)#

highlight()

View Helpers Miscellaneous Functions string controller

Highlights the phrase(s) everywhere in the text if found by wrapping them in span tags.

Name Type Required Default Description
text string Yes Text to search in.
phrase string No Phrase (or list of phrases) to highlight. This argument is also aliased as phrases.
delimiter string No , Delimiter to use when passing in multiple phrases.
tag string No span HTML tag to use to wrap the highlighted phrase(s).
class string No highlight Class to use in the tags wrapping highlighted phrase(s).
encode boolean No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- Will output: You searched for: <span class="highlight">CFWheels --->
#highlight(text="You searched for: CFWheels", phrases="CFWheels")#

hourSelectTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing one select form control for the hours of the day based on the supplied name.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
selected string No The day that should be selected initially.
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
twelveHour boolean No false whether to display the hours in 24 or 12 hour format. 12 hour format has AM/PM drop downs
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!---This "Tag" version of the function accepts a `name` and `selected` instead of binding to a model object --->
#hourSelectTag(name="hourOfMeeting", selected=params.hourOfMeeting)#

<!---Show 12 hours instead of 24 --->
#hourSelectTag(name="hourOfMeeting", selected=params.hourOfMeeting, twelveHour=true)#

humanize()

Global Helpers String Functions string controller model mapper migrator migration tabledefinition

Returns readable text by capitalizing and converting camel casing to multiple words.

Name Type Required Default Description
text string Yes Text to humanize.
except string No A list of strings (space separated) to replace within the output.
<!--- Humanize a string, will result in "Wheels Is A Framework" --->
#humanize("wheelsIsAFramework")#

<!--- Humanize a string, force wheels to replace "Cfml" with "CFML" --->
#humanize("wheelsIsACfmlFramework", "CFML")#

hyphenize()

Global Helpers String Functions string controller model mapper migrator migration tabledefinition

Converts camelCase strings to lowercase strings with hyphens as word delimiters instead. Example: myVariable becomes my-variable.

Name Type Required Default Description
string string Yes The string to hyphenize.
<!---Outputs "my-blog-post" --->
#hyphenize("myBlogPost")#

imageTag()

View Helpers Asset Functions string controller

Returns an img tag. If the image is stored in the local images folder, the tag will also set the width, height, and alt attributes for you. You can pass any additional arguments (e.g. class, rel, id), and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
source string Yes The file name of the image if it's available in the local file system (i.e. ColdFusion will be able to access it). Provide the full URL if the image is on a remote server.
onlyPath boolean No true
host string No
protocol string No
port numeric No 0
encode boolean No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
required boolean No true
<!--- Outputs an `img` tag for `images/logo.png` --->
#imageTag("logo.png")#

<!--- Outputs an `img` tag for `http://cfwheels.org/images/logo.png` --->
#imageTag(source="http://cfwheels.org/images/logo.png", alt="ColdFusion on Wheels")#

<!--- Outputs an `img` tag with the `class` attribute set --->
#imageTag(source="logo.png", class="logo")#

includeContent()

View Helpers Miscellaneous Functions string controller

Used to output the content for a particular section in a layout.

Name Type Required Default Description
name string No body Name of layout section to return content for.
defaultValue string No What to display as a default if the section is not defined.
<!--- In your view template, let's say `views/blog/post.cfm--->
contentFor(head='<meta name="robots" content="noindex,nofollow">');
contentFor(head='<meta name="author" content="[email protected]">');

// In `views/layout.cfm`
<html>
	<head>
	    <title>My Site</title>
	    #includeContent("head")#
	</head>
	<body>
		<cfoutput>
			#includeContent()#
		</cfoutput>
	</body>
</html>

includedInObject()

View Helpers Form Association Functions boolean controller

Used as a shortcut to check if the specified IDs are a part of the main form object. This method should only be used for hasMany associations.

Name Type Required Default Description
objectName string Yes Name of the variable containing the parent object to represent with this form field.
association string Yes Name of the association set in the parent object to represent with this form field.
keys string Yes Primary keys associated with this form field. Note that these keys should be listed in the order that they appear in the database table.
// Check to see if the customer is subscribed to the Swimsuit Edition. Note that the order of the `keys` argument should match the order of the `customerid` and `publicationid` columns in the `subscriptions` join table
if(!includedInObject(objectName="customer", association="subscriptions", keys="#customer.key()#,#swimsuitEdition.id#")){
    assignSalesman(customer);
}

includeLayout()

View Helpers Miscellaneous Functions string controller

Includes the contents of another layout file. This is usually used to include a parent layout from within a child layout.

Name Type Required Default Description
name string No layout Name of the layout file to include.
<!--- Make sure that the `sidebar` value is provided for the parent layout --->
<cfsavecontent variable="categoriesSidebar">
	<cfoutput>
		<ul>
			#includePartial(categories)#
		</ul>
	</cfoutput>
</cfsavecontent>
contentFor(sidebar=categoriesSidebar);

<!---Include parent layout at `views/layout.cfm`--->
#includeLayout("/layout.cfm")#

includePartial()

View Helpers Miscellaneous Functions string controller

Includes the specified partial file in the view. Similar to using cfinclude but with the ability to cache the result and use CFWheels-specific file look-up. By default, CFWheels will look for the file in the current controller's view folder. To include a file relative from the base views folder, you can start the path supplied to partial with a forward slash.

Name Type Required Default Description
partial any Yes The name of the partial file to be used. Prefix with a leading slash (/) if you need to build a path from the root views folder. Do not include the partial filename's underscore and file extension. If you want to have CFWheels display the partial for a single model object, array of model objects, or a query, pass a variable containing that data into this argument.
group string No If passing a query result set for the partial argument, use this to specify the field to group the query by. A new query will be passed into the partial template for you to iterate over.
cache any No Number of minutes to cache the content for.
layout string No The layout to wrap the content in. Prefix with a leading slash (/) if you need to build a path from the root views folder. Pass false to not load a layout at all.
spacer string No HTML or string to place between partials when called using a query.
dataFunction any No true Name of controller function to load data from.

// If we're in the "sessions" controller, CFWheels will include the file "views/sessions/_login.cfm".  
#includePartial("login")# 

// CFWheels will include the file "views/shared/_button.cfm".  
#includePartial(partial="/shared/button")# 

// If we're in the "posts" controller and the "posts" variable includes a query result set, CFWheels will loop through the record set and include the file "views/posts/_post.cfm" for each record.  
<cfset posts = model("post").findAll()> 
#includePartial(posts)# 

// We can also override the template file loaded for the example above.  
#includePartial(partial="/shared/post", query=posts)# 

// The same works when passing a model instance.  
<cfset post = model("post").findByKey(params.key)> #includePartial(post)# 
#includePartial(partial="/shared/post", object=post)# 

// The same works when passing an array of model objects.  
<cfset posts = model("post").findAll(returnAs="objects")> 
#includePartial(posts)# 
#includePartial(partial="/shared/post", objects=posts)# 
</cfoutput>

integer()

Migrator Table Definition Functions any tabledefinition

adds integer columns to table definition

Name Type Required Default Description
columnNames string No
limit numeric No
default string No
null boolean No

invokeWithTransaction()

Model Class Miscellaneous Functions any model

Runs the specified method within a single database transaction.

Name Type Required Default Description
method string Yes Model method to run.
transaction string No commit Set this to commit to update the database, rollback to run all the database queries but not commit them, or none to skip transaction handling altogether.
isolation string No read_committed Isolation level to be passed through to the cftransaction tag. See your CFML engine's documentation for more details about cftransaction's isolation attribute.
// This is the method to be run inside a transaction.
public boolean function transferFunds(required any personFrom, required any personTo, required numeric amount) {
	if (arguments.personFrom.withdraw(arguments.amount) && arguments.personTo.deposit(arguments.amount)) {
		return true;
	} else {
		return false;
	}
}

local.david = model("Person").findOneByName("David");
local.mary = model("Person").findOneByName("Mary");
invokeWithTransaction(method="transferFunds", personFrom=local.david, personTo=local.mary, amount=100);

isAjax()

Controller Miscellaneous Functions boolean controller

Returns whether the page was called from JavaScript or not.

requestIsAjax = isAjax();

isClass()

Model Class Miscellaneous Functions string model

Use this method to check whether you are currently in a class-level object.

// Use the passed in `id` when we're already in an instance
function memberIsAdmin(){
	if(isClass()){
		return this.findByKey(arguments.id).admin;
	} else {
		return this.admin;
	}
}

isDelete()

Controller Miscellaneous Functions boolean controller

Returns whether the request was a DELETE request or not.

isGet()

Controller Miscellaneous Functions boolean controller

Returns whether the request was a normal GET request or not.

requestIsGet = isGet();

isHead()

Controller Miscellaneous Functions boolean controller

Returns whether the request was a HEAD request or not.

isInstance()

Model Class Miscellaneous Functions boolean model

Use this method to check whether you are currently in an instance object.

// Use the passed in `id` when we're not already in an instance
function memberIsAdmin(){
	if(isInstance()){
		return this.admin;
	} else {
		return this.findByKey(arguments.id).admin;
	}
}

isNew()

Model Object Miscellaneous Functions boolean model

Returns true if this object hasn't been saved yet (in other words, no matching record exists in the database yet). Returns false if a record exists.

// Create a new object and then check if it is new (yes, this example is ridiculous. It makes more sense in the context of callbacks for example)
employee = model("employee").new()>
<cfif employee.isNew()>
    // Do something...
</cfif>

isOptions()

Controller Miscellaneous Functions boolean controller

Returns whether the request was an OPTIONS request or not.

isPatch()

Controller Miscellaneous Functions boolean controller

Returns whether the request was a PATCH request or not.

isPersisted()

Model Object Miscellaneous Functions boolean model

Returns true if this object has been persisted to the database or was loaded from the database via a finder. Returns false if the record has not been persisted to the database.

isPost()

Controller Miscellaneous Functions boolean controller

Returns whether the request came from a form POST submission or not.

requestIsPost = isPost();

isPut()

Controller Miscellaneous Functions boolean controller

Returns whether the request was a PUT request or not.

isSecure()

Controller Miscellaneous Functions boolean controller

Returns whether CFWheels is communicating over a secure port.

// Redirect non-secure connections to the secure version
if (!isSecure())
{
	redirectTo(protocol="https");
}

javaScriptIncludeTag()

View Helpers Asset Functions string controller

Returns a script tag for a JavaScript file (or several) based on the supplied arguments.

Name Type Required Default Description
sources string No The name of one or many JavaScript files in the javascripts folder, minus the .js extension. Pass a full URL to access an external JavaScript file. Can also be called with the source argument.
type string No text/javascript The type attribute for the script tag.
head boolean No false Set to true to place the output in the head area of the HTML page instead of the default behavior (which is to place the output where the function is called from).
delim string No , The delimiter to use for the list of JavaScript files.
encode boolean No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- View Code --->
<head>
    <!--- Includes `javascripts/main.js` --->
    #javaScriptIncludeTag("main")#

    <!--- Includes `javascripts/blog.js` and `javascripts/accordion.js` --->
    #javaScriptIncludeTag("blog,accordion")#
    
    <!--- Includes external JavaScript file --->
    #javaScriptIncludeTag("https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js")#
</head>

<body>
    <!--- Will still appear in the `head` --->
    #javaScriptIncludeTag(source="tabs", head=true)#
</body>

key()

Model Object Miscellaneous Functions string model

Returns the value of the primary key for the object. If you have a single primary key named id, then someObject.key() is functionally equivalent to someObject.id. This method is more useful when you do dynamic programming and don't know the name of the primary key or when you use composite keys (in which case it's convenient to use this method to get a list of both key values returned).

Name Type Required Default Description
// Get an object and then get the primary key value(s)
employee = model("employee").findByKey(params.key);
val = employee.key();

linkTo()

View Helpers Link Functions string controller

Creates a link to another page in your application. Pass in the name of a route to use your configured routes or a controller/action/key combination. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
text string No The text content of the link.
route string No Name of a route that you have configured in config/routes.cfm.
controller string No Name of the controller to include in the URL.
action string No Name of the action to include in the URL.
key any No Key(s) to include in the URL.
params string No Any additional parameters to be set in the query string (example: wheels=cool&x=y). Please note that CFWheels uses the & and = characters to split the parameters and encode them properly for you. However, if you need to pass in & or = as part of the value, then you need to encode them (and only them), example: a=cats%26dogs%3Dtrouble!&b=1.
anchor string No Sets an anchor name to be appended to the path.
onlyPath boolean No true If true, returns only the relative URL (no protocol, host name or port).
host string No Set this to override the current host.
protocol string No Set this to override the current protocol.
port numeric No 0 Set this to override the current port number.
href string No Pass a link to an external site here if you want to bypass the CFWheels routing system altogether and link to an external URL.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
#linkTo(text="Log Out", controller="account", action="logout")#
<!--- Ouputs: <a href="/account/logout">Log Out</a> --->

<!--- If you're already in the `account` controller, CFWheels will assume that's where you want the link to point --->
#linkTo(text="Log Out", action="logout")#
<!--- Ouputs: <a href="/account/logout">Log Out</a> --->

#linkTo(text="View Post", controller="blog", action="post", key=99)#
<!--- Ouputs: <a href="/blog/post/99">View Post</a> --->

#linkTo(text="View Settings", action="settings", params="show=all&amp;sort=asc")#
<!--- Ouputs: <a href="/account/settings?show=all&amp;amp;sort=asc">View Settings</a> --->

<!--- Given that a `userProfile` route has been configured in `config/routes.cfm` --->
#linkTo(text="Joe's Profile", route="userProfile", userName="joe")#
<!--- Ouputs: <a href="/user/joe">Joe's Profile</a> --->

<!--- Link to an external website --->
#linkTo(text="ColdFusion Framework", href="http://cfwheels.org/")#
<!--- Ouputs: <a href="http://cfwheels.org/">ColdFusion Framework</a> --->

<!--- Give the link `class` and `id` attributes --->
#linkTo(text="Delete Post", action="delete", key=99, class="delete", id="delete-99")#
<!--- Ouputs: <a class="delete" href="/blog/delete/99" id="delete-99">Delete Post</a> --->

mailTo()

View Helpers Link Functions string controller

Creates a mailto link tag to the specified email address, which is also used as the name of the link unless name is specified.

Name Type Required Default Description
emailAddress string Yes The email address to link to.
name string No A string to use as the link text ("Joe" or "Support Department", for example).
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
#mailTo(emailAddress="[email protected]", name="Contact our Webmaster")#
<!--- Outputs: <a href="mailto:[email protected]">Contact our Webmaster</a> --->

mapper()

Configuration Routing struct controller model migrator migration tabledefinition

Returns the mapper object used to configure your application's routes. Usually you will use this method in config/routes.cfm to start chaining route mapping methods like resources, namespace, etc.

Name Type Required Default Description
restful boolean No true Whether to turn on RESTful routing or not. Not recommended to set. Will probably be removed in a future version of wheels, as RESTful routes are the default.
methods boolean No [runtime expression] If not RESTful, then specify allowed routes. Not recommended to set. Will probably be removed in a future version of wheels, as RESTful routes are the default.
mapFormat boolean No true This is useful for providing formats via URL like json, xml, pdf, etc. Set to false to disable automatic .[format] generation for resource based routes

maximum()

Model Class Statistics Functions any model

Calculates the maximum value for a given property. Uses the SQL function MAX. If no records can be found to perform the calculation on you can use the ifNull argument to decide what should be returned.

Name Type Required Default Description
property string Yes Name of the property to get the highest value for (must be a property of a numeric data type).
where string No Maps to the WHERE clause of the query (or HAVING when necessary). The following operators are supported: =, !=, <>, <, <=, >, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, and OR (note that the key words need to be written in upper case). You can also use parentheses to group statements. You do not need to specify the table name(s); CFWheels will do that for you.
include string No Associations that should be included in the query using INNER or LEFT OUTER joins (which join type that is used depends on how the association has been set up in your model). If all included associations are set on the current model, you can specify them in a list (e.g. department,addresses,emails). You can build more complex include strings by using parentheses when the association is set on an included model, like album(artist(genre)), for example. These complex include strings only work when returnAs is set to query though.
parameterize any No true
ifNull any No The value returned if no records are found. Common usage is to set this to 0 to make sure a numeric value is always returned instead of a blank string.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
group string No Maps to the GROUP BY clause of the query. You do not need to specify the table name(s); CFWheels will do that for you.
// Get the amount of the highest salary for all employees
highestSalary = model("employee").maximum("salary");

// Get the amount of the highest salary for employees in a given department
highestSalary = model("employee").maximum(property="salary", where="departmentId=#params.key#");

// Make sure a numeric value is always returned, even if no records are found to calculate the maximum for
highestSalary = model("employee").maximum(property="salary", where="salary > #params.minSalary#", ifNull=0);

member()

Configuration Routing struct mapper

Scope routes within a nested resource which require use of the primary key as part of the URL pattern; A member route will require an ID, because it acts on a member. photos/1/preview is an example of a member route, because it acts on (and displays) a single object.

<cfscript>

mapper()
    // Create a route like `photos/1/preview`
    .resources(name="photos", nested=true)
        .member()
            .get("preview")
        .end()
    .end()
.end();

</cfscript>

migrateTo()

Migrator General Functions string migrator

Migrates database to a specified version. Whilst you can use this in your application, the recommended useage is via either the CLI or the provided GUI interface

Name Type Required Default Description
version string No The Database schema version to migrate to
// Migrate to a specific version
// Returns a message with the result
result=application.wheels.migrator.migrateTo(version);

migrateToLatest()

Migrator General Functions string migrator

Shortcut function to migrate to the latest version

mimeTypes()

Global Helpers Miscellaneous Functions string controller model migrator migration tabledefinition

Returns an associated MIME type based on a file extension.

Name Type Required Default Description
extension string Yes The extension to get the MIME type for.
fallback string No application/octet-stream The fallback MIME type to return.
// Get the internally-stored MIME type for `xls`
mimeType = mimeTypes("xls");

// Get the internally-stored MIME type for a dynamic value. Fall back to a MIME type of `text/plain` if it's not found
mimeType = mimeTypes(extension=params.type, fallback="text/plain");

minimum()

Model Class Statistics Functions any model

Calculates the minimum value for a given property. Uses the SQL function MIN. If no records can be found to perform the calculation on you can use the ifNull argument to decide what should be returned.

Name Type Required Default Description
property string Yes Name of the property to get the lowest value for (must be a property of a numeric data type).
where string No Maps to the WHERE clause of the query (or HAVING when necessary). The following operators are supported: =, !=, <>, <, <=, >, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, and OR (note that the key words need to be written in upper case). You can also use parentheses to group statements. You do not need to specify the table name(s); CFWheels will do that for you.
include string No Associations that should be included in the query using INNER or LEFT OUTER joins (which join type that is used depends on how the association has been set up in your model). If all included associations are set on the current model, you can specify them in a list (e.g. department,addresses,emails). You can build more complex include strings by using parentheses when the association is set on an included model, like album(artist(genre)), for example. These complex include strings only work when returnAs is set to query though.
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
ifNull any No The value returned if no records are found. Common usage is to set this to 0 to make sure a numeric value is always returned instead of a blank string.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
group string No Maps to the GROUP BY clause of the query. You do not need to specify the table name(s); CFWheels will do that for you.
// Get the amount of the lowest salary for all employees
lowestSalary = model("employee").minimum("salary");

// Get the amount of the lowest salary for employees in a given department
lowestSalary = model("employee").minimum(property="salary", where="departmentId=#params.key#");

// Make sure a numeric amount is always returned, even when there were no records analyzed by the query
lowestSalary = model("employee").minimum(property="salary", where="salary BETWEEN #params.min# AND #params.max#", ifNull=0);

minuteSelectTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing one select form control for the minutes of an hour based on the supplied name.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
selected string No The day that should be selected initially.
minuteStep numeric No 1 Pass in 10 to only show minute 10, 20, 30, etc.
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
// This "Tag" version of the function accepts a `name` and `selected` instead of binding to a model object 
<cfoutput>
    #minuteSelectTag(name="minuteOfMeeting", value=params.minuteOfMeeting)#
</cfoutput>

// Only show 15-minute intervals 
<cfoutput>
	#minuteSelectTag(name="minuteOfMeeting", value=params.minuteOfMeeting, minuteStep=15)#
</cfoutput>

model()

Global Helpers Miscellaneous Functions any controller model migrator migration tabledefinition

Returns a reference to the requested model so that class level methods can be called on it.

Name Type Required Default Description
name string Yes Name of the model to get a reference to.
// The `model("author")` part of the code below gets a reference to the model from the application scope, and then the `findByKey` class level method is called on it
authorObject = model("author").findByKey(1);

monthSelectTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing a select form control for the months of the year based on the supplied name.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
selected string No The month that should be selected initially.
monthDisplay string No names Pass in names, numbers, or abbreviations to control display.
monthNames string No January,February,March,April,May,June,July,August,September,October,November,December [see:dateSelect].
monthAbbreviations string No Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec [see:dateSelect].
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
// This "Tag" version of the function accepts a `name` and `selected` instead of binding to a model object 
<cfoutput>
    #monthSelectTag(name="monthOfBirthday", selected=params.monthOfBirthday)#
</cfoutput>

namespace()

Configuration Routing struct mapper

Scopes any the controllers for any routes configured within this block to a subfolder (package) and also adds the package name to the URL.

Name Type Required Default Description
name string Yes Name to prepend to child route names.
package string No [runtime expression] Subfolder (package) to reference for controllers. This defaults to the value provided for name.
path string No [runtime expression] Subfolder path to add to the URL.
<cfscript>

mapper()
    .namespace("api")
        .namespace("v2")
            // Route name:  apiV2Products
            // Example URL: /api/v2/products/1234
            // Controller:  api.v2.Products
            .resources("products")
        .end()

        .namespace("v1")
            // Route name:  apiV1Users
            // Example URL: /api/v1/users
            // Controller:  api.v1.Users
            .get(name="users", to="users##index")
        .end()
    .end()

    .namespace(name="foo", package="foos", path="foose")
        // Route name:  fooBars
        // Example URL: /foose/bars
        // Controller:  foos.Bars
        .post(name="bars", to="bars##create")
    .end()
.end();

</cfscript>

nestedProperties()

Model Configuration Miscellaneous Functions void model

Allows for nested objects, structs, and arrays to be set from params and other generated data.

Name Type Required Default Description
association string No The association (or list of associations) you want to allow to be set through the params. This argument is also aliased as associations.
autoSave boolean No true Whether to save the association(s) when the parent object is saved.
allowDelete boolean No false Set this to true to tell CFWheels to look for the property _delete in your model. If present and set to a value that evaluates to true, the model will be deleted when saving the parent.
sortProperty string No Set this to a property on the object that you would like to sort by. The property should be numeric, should start with 1, and should be consecutive. Only valid with hasMany associations.
rejectIfBlank string No A list of properties that should not be blank. If any of the properties are blank, any CRUD operations will be rejected.
// In `models/User.cfc`, allow for `groupEntitlements` to be saved and deleted through the `user` object.
function config(){
	hasMany("groupEntitlements");
	nestedProperties(association="groupEntitlements", allowDelete=true);
}

new()

Model Class Create Functions any model

Creates a new object based on supplied properties and returns it. The object is not saved to the database, it only exists in memory. Property names and values can be passed in either using named arguments or as a struct to the properties argument.

Name Type Required Default Description
properties struct No [runtime expression] The properties you want to set on the object (can also be passed in as named arguments).
callbacks boolean No true Set to false to disable callbacks for this method.
// Create a new author in memory (not saved to the database)
newAuthor = model("author").new();

// Create a new author based on properties in a struct
newAuthor = model("author").new(params.authorStruct);

// Create a new author by passing in named arguments
newAuthor = model("author").new(firstName="John", lastName="Doe");

// If you have a `hasOne` or `hasMany` association setup from `customer` to `order`, you can do a scoped call. (The `newOrder` method below will call `model("order").new(customerId=aCustomer.id)` internally.)
aCustomer = model("customer").findByKey(params.customerId);
anOrder = aCustomer.newOrder(shipping=params.shipping);

obfuscateParam()

Global Helpers Miscellaneous Functions string controller model migrator migration tabledefinition

Obfuscates a value. Typically used for hiding primary key values when passed along in the URL.

Name Type Required Default Description
param any Yes The value to obfuscate.
// Obfuscate the primary key value `99`
newValue = obfuscateParam(99);

onlyProvides()

Controller Provides Functions void controller

Use this in an individual controller action to define which formats the action will respond with. This can be used to define provides behavior in individual actions or to override a global setting set with provides in the controller's config().

Name Type Required Default Description
formats string No Formats to instruct the controller to provide. Valid values are html (the default), xml, json, csv, pdf, and xls.
action string No [runtime expression] Name of action, defaults to current.
// This will only provide the `html` type and will ignore what was defined in the call to `provides()` in the `config()` function
onlyProvides("html");

onMissingMethod()

Model Class Miscellaneous Functions any model

This method is not designed to be called directly from your code, but provides functionality for dynamic finders such as findOneByEmail()

Name Type Required Default Description
missingMethodName string Yes
missingMethodArguments struct Yes

package()

Configuration Routing struct mapper

Scopes any the controllers for any routes configured within this block to a subfolder (package) without adding the package name to the URL.

Name Type Required Default Description
name string Yes Name to prepend to child route names.
package string No [runtime expression] Subfolder (package) to reference for controllers. This defaults to the value provided for name.
<cfscript>

mapper()
    .package("public")
        // Example URL: /products/1234
        // Controller:  public.Products
        .resources("products")
    .end()

    // Example URL: /users/4321
    // Controller:  Users
    .resources(name="users", nested=true)
        // Calling `package` here is useful to scope nested routes for the `users`
        // resource into a subfolder.
        .package("users")
            // Example URL: /users/4321/profile
            // Controller:  users.Profiles
            .resource("profile")
        .end()
    .end()
.end();

</cfscript>

passwordField()

View Helpers Form Object Functions string controller

Builds and returns a string containing a password field form control based on the supplied objectName and property. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
objectName any Yes The variable name of the object to build the form control for.
property string Yes The name of the property to use in the form control.
association string No The name of the association that the property is located on. Used for building nested forms that work with nested properties. If you are building a form with deep nesting, simply pass in a list to the nested object, and CFWheels will figure it out.
position string No The position used when referencing a hasMany relationship in the association argument. Used for building nested forms that work with nested properties. If you are building a form with deep nestings, simply pass in a list of positions, and CFWheels will figure it out.
label string No useDefaultLabel The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
errorElement string No span HTML tag to wrap the form control with when the object contains errors.
errorClass string No field-with-errors The class name of the HTML tag that wraps the form control when there are errors.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
// Provide a `label` and the required `objectName` and `property`
<cfoutput>
    #passwordField(label="Password", objectName="user", property="password")#
</cfoutput>

// Display fields for passwords provided by the `passwords` association and nested properties
<fieldset>
	<legend>Passwords</legend>
	<cfloop from="1" to="#ArrayLen(user.passwords)#" index="i">
		#passwordField(label="Password ##i#", objectName="user", association="passwords", position=i, property="password")#
	</cfloop>
</fieldset>

passwordFieldTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing a password field form control based on the supplied name. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
value string No Value to populate in tag's value attribute.
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
// Basic usage usually involves a `label`, `name`, and `value` 
<cfoutput>
    #passwordFieldTag(label="Password", name="password", value=params.password)#
</cfoutput>

patch()

Configuration Routing struct mapper

Create a route that matches a URL requiring an HTTP PATCH method. We recommend using this matcher to expose actions that update database records.

Name Type Required Default Description
name string No Camel-case name of route to reference when build links and form actions (e.g., blogPost).
pattern string No Overrides the URL pattern that will match the route. The default value is a dasherized version of name (e.g., a name of blogPost generates a pattern of blog-post).
to string No Set controller##action combination to map the route to. You may use either this argument or a combination of controller and action.
controller string No Map the route to a given controller. This must be passed along with the action argument.
action string No Map the route to a given action within the controller. This must be passed along with the controller argument.
package string No Indicates a subfolder that the controller will be referenced from (but not added to the URL pattern). For example, if you set this to admin, the controller will be located at admin/YourController.cfc, but the URL path will not contain admin/.
on string No If this route is within a nested resource, you can set this argument to member or collection. A member route contains a reference to the resource's key, while a collection route does not.
redirect string No Redirect via 302 to this URL when this route is matched. Has precedence over controller/action. Use either an absolute link like /about/, or a full canonical link.
<cfscript>

mapper()
    // Route name:  ghostStory
    // Example URL: /ghosts/666/stories/616
    // Controller:  Stories
    // Action:      update
    .patch(name="ghostStory", pattern="ghosts/[ghostKey]/stories/[key]", to="stories##update")

    // Route name:  goblins
    // Example URL: /goblins
    // Controller:  Goblins
    // Action:      update
    .patch(name="goblins", controller="goblins", action="update")

    // Route name:  heartbeat
    // Example URL: /heartbeat
    // Controller:  Sessions
    // Action:      update
    .patch(name="heartbeat", to="sessions##update")

    // Route name:  usersPreferences
    // Example URL: /preferences
    // Controller:  users.Preferences
    // Action:      update
    .patch(name="preferences", to="preferences##update", package="users")

    // Route name:  orderShipment
    // Example URL: /shipments/5432
    // Controller:  orders.Shipments
    // Action:      update
    .patch(
        name="shipment",
        pattern="shipments/[key]",
        to="shipments##update",
        package="orders"
    )

    // Example scoping within a nested resource
    .resources(name="subscribers", nested=true)
        // Route name:  launchSubscribers
        // Example URL: /subscribers/3209/launch
        // Controller:  Subscribers
        // Action:      launch
        .patch(name="launch", to="subscribers##update", on="collection")

        // Route name:  discontinueSubscriber
        // Example URL: /subscribers/2251/discontinue
        // Controller:  Subscribers
        // Action:      discontinue
        .patch(name="discontinue", to="subscribers##discontinue", on="member")
    .end()
.end();

</cfscript>

pluginNames()

Global Helpers Miscellaneous Functions string controller model migrator migration tabledefinition

Returns a list of the names of all installed plugins.

// Check if the Scaffold plugin is installed 
<cfif ListFindNoCase("scaffold", pluginNames())>
    // do something cool 
</cfif>

pluralize()

Global Helpers String Functions string controller model mapper migrator migration tabledefinition

Returns the plural form of the passed in word. Can also pluralize a word based on a value passed to the count argument. CFWheels stores a list of words that are the same in both singular and plural form (e.g. "equipment", "information") and words that don't follow the regular pluralization rules (e.g. "child" / "children", "foot" / "feet"). Use get("uncountables") / set("uncountables", newList) and get("irregulars") / set("irregulars", newList) to modify them to suit your needs.

Name Type Required Default Description
word string Yes The word to pluralize.
count numeric No -1 Pluralization will occur when this value is not 1.
returnCount boolean No true Will return count prepended to the pluralization when true and count is not -1.
// Pluralize a word, will result in "people" 
#pluralize("person")#

// Pluralize based on the count passed in 
Your search returned #pluralize(word="person", count=users.RecordCount)#

post()

Configuration Routing struct mapper

Create a route that matches a URL requiring an HTTP POST method. We recommend using this matcher to expose actions that create database records.

Name Type Required Default Description
name string No Camel-case name of route to reference when build links and form actions (e.g., blogPosts).
pattern string No Overrides the URL pattern that will match the route. The default value is a dasherized version of name (e.g., a name of blogPosts generates a pattern of blog-posts).
to string No Set controller##action combination to map the route to. You may use either this argument or a combination of controller and action.
controller string No Map the route to a given controller. This must be passed along with the action argument.
action string No Map the route to a given action within the controller. This must be passed along with the controller argument.
package string No Indicates a subfolder that the controller will be referenced from (but not added to the URL pattern). For example, if you set this to admin, the controller will be located at admin/YourController.cfc, but the URL path will not contain admin/.
on string No If this route is within a nested resource, you can set this argument to member or collection. A member route contains a reference to the resource's key, while a collection route does not.
redirect string No Redirect via 302 to this URL when this route is matched. Has precedence over controller/action. Use either an absolute link like /about/, or a full canonical link.
<cfscript>

mapper()
    // Route name:  widgets
    // Example URL: /sites/918/widgets
    // Controller:  Widgets
    // Action:      create
    .post(name="widgets", pattern="sites/[siteKey]/widgets", to="widgets##create")

    // Route name:  wadgets
    // Example URL: /wadgets
    // Controller:  Wadgets
    // Action:      create
    .post(name="wadgets", controller="wadgets", action="create")

    // Route name:  authenticate
    // Example URL: /oauth/token.json
    // Controller:  Tokens
    // Action:      create
    .post(name="authenticate", pattern="oauth/token.json", to="tokens##create")

    // Route name:  usersPreferences
    // Example URL: /preferences
    // Controller:  users.Preferences
    // Action:      create
    .post(name="preferences", to="preferences##create", package="users")

    // Route name:  extranetOrders
    // Example URL: /buy-now/orders
    // Controller:  extranet.Orders
    // Action:      create
    .post(
        name="orders",
        pattern="buy-now/orders",
        to="orders##create",
        package="extranet"
    )

    // Example scoping within a nested resource
    .resources(name="customers", nested=true)
        // Route name:  leadsCustomers
        // Example URL: /customers/leads
        // Controller:  Leads
        // Action:      create
        .post(name="leads", to="leads##create", on="collection")

        // Route name:  cancelCustomer
        // Example URL: /customers/3209/cancel
        // Controller:  Cancellations
        // Action:      create
        .post(name="cancel", to="cancellations##create", on="member")
    .end()
.end();

</cfscript>

primaryKey()

Model Class Miscellaneous Functions string model

Returns the name of the primary key for this model's table. This is determined through database introspection. If composite primary keys have been used, they will both be returned in a list. This function is also aliased as primaryKeys().

Name Type Required Default Description
position numeric No 0 If you are accessing a composite primary key, pass the position of a single key to fetch.
// Get the name of the primary key of the table mapped to the `employee` model (which is the `employees` table by default)
keyName = model("employee").primaryKey();

primaryKey()

Migrator Table Definition Functions any tabledefinition

Adds a primary key definition to the table. this method also allows for multiple primary keys.

Name Type Required Default Description
name string Yes
type string No integer
autoIncrement boolean No false
limit numeric No
precision numeric No
scale numeric No
references string No
onUpdate string No
onDelete string No

primaryKeys()

Model Class Miscellaneous Functions string model

Alias for primaryKey(). Use this for better readability when you're accessing multiple primary keys.

Name Type Required Default Description
position numeric No 0 If you are accessing a composite primary key, pass the position of a single key to fetch.
// Get a list of the names of the primary keys in the table mapped to the `employee` model (which is the `employees` table by default)
keyNames = model("employee").primaryKeys();

processAction()

Controller Miscellaneous Functions boolean controller

Process the specified action of the controller. This is exposed in the API primarily for testing purposes; you would not usually call it directly unless in the test suite.

Name Type Required Default Description
includeFilters string No true Set to before to only execute "before" filters, after to only execute "after" filters or false to skip all filters. This argument is generally inherited from the processRequest function during unit test execution.

processRequest()

Controller Miscellaneous Functions any controller model migrator migration tabledefinition

Creates a controller and calls an action on it. Which controller and action that's called is determined by the params passed in. Returns the result of the request either as a string or in a struct with body, emails, files, flash, redirect, status, and type. Primarily used for testing purposes.

Name Type Required Default Description
params struct Yes The params struct to use in the request (make sure that at least controller and action are set).
method string No get The HTTP method to use in the request (get, post etc).
returnAs string No Pass in struct to return all information about the request instead of just the final output (body).
rollback string No false Pass in true to roll back all database transactions made during the request.
includeFilters string No true Set to before to only execute "before" filters, after to only execute "after" filters or false to skip all filters.

properties()

Model Object Miscellaneous Functions struct model

Returns a structure of all the properties with their names as keys and the values of the property as values.

Name Type Required Default Description
returnIncluded boolean No true Whether to return nested properties or not.
// Get a structure of all the properties for an object
user = model("user").findByKey(1);
props = user.properties();

property()

Model Configuration Miscellaneous Functions void model

Use this method to map an object property to either a table column with a different name than the property or to a SQL expression. You only need to use this method when you want to override the default object relational mapping that CFWheels performs.

Name Type Required Default Description
name string Yes The name that you want to use for the column or SQL function result in the CFML code.
column string No The name of the column in the database table to map the property to.
sql string No An SQL expression to use to calculate the property value.
label string No A custom label for this property to be referenced in the interface and error messages.
defaultValue string No A default value for this property.
select boolean No true Whether to include this property by default in SELECT statements
dataType string No char Specify the column dataType for this property
automaticValidations boolean No Enable / disable automatic validations for this property.
// Tell Wheels that when we are referring to `firstName` in the CFML code, it should translate to the `STR_USERS_FNAME` column when interacting with the database instead of the default (which would be the `firstname` column)
property(name="firstName", column="STR_USERS_FNAME");

// Tell Wheels that when we are referring to `fullName` in the CFML code, it should concatenate the `STR_USERS_FNAME` and `STR_USERS_LNAME` columns
property(name="fullName", sql="STR_USERS_FNAME + ' ' + STR_USERS_LNAME");

// Tell Wheels that when displaying error messages or labels for form fields, we want to use `First name(s)` as the label for the `STR_USERS_FNAME` column
property(name="firstName", label="First name(s)");

// Tell Wheels that when creating new objects, we want them to be auto-populated with a `firstName` property of value `Dave`
property(name="firstName", defaultValue="Dave");

propertyIsBlank()

Model Object Miscellaneous Functions boolean model

Returns true if the specified property doesn't exist on the model or is an empty string. This method is the inverse of propertyIsPresent().

Name Type Required Default Description
property string Yes Name of property to inspect.

propertyIsPresent()

Model Object Miscellaneous Functions boolean model

Returns true if the specified property exists on the model and is not a blank string.

Name Type Required Default Description
property string Yes Name of property to inspect.
// Get an object, set a value and then see if the property exists
employee = model("employee").new();
employee.firstName = "dude";
return employee.propertyIsPresent("firstName"); // Returns true

employee.firstName = "">
return employee.propertyIsPresent("firstName"); // Returns false

propertyNames()

Model Class Miscellaneous Functions string model

Returns a list of property names ordered by their respective column's ordinal position in the database table. Also includes calculated property names that will be generated by the CFWheels ORM.

// Get a list of the property names in use in the user model
propNames = model("user").propertyNames();

protectedProperties()

Model Configuration Miscellaneous Functions void model

Use this method to specify which properties cannot be set through mass assignment.

Name Type Required Default Description
properties string No Property name (or list of property names) that are not allowed to be altered through mass assignment.
// In `models/User.cfc`, `firstName` and `lastName` cannot be changed through mass assignment operations like `updateAll()`.
function config(){
	protectedProperties("firstName,lastName");
}

protectsFromForgery()

Controller Configuration Functions any controller

Tells CFWheels to protect POSTed requests from CSRF vulnerabilities. Instructs the controller to verify that params.authenticityToken or X-CSRF-Token HTTP header is provided along with the request containing a valid authenticity token. Call this method within a controller's config method, preferably the base Controller.cfc file, to protect the entire application.

Name Type Required Default Description
with string No exception How to handle invalid authenticity token checks. Valid values are error (throws a Wheels.InvalidAuthenticityToken error) and abort (aborts the request silently and sends a blank response to the client).
only string No List of actions that this check should only run on. Leave blank for all.
except string No List of actions that this check should be omitted from running on. Leave blank for no exceptions.

provides()

Controller Configuration Functions void controller

Defines formats that the controller will respond with upon request. The format can be requested through a URL variable called format, by appending the format name to the end of a URL as an extension (when URL rewriting is enabled), or in the request header.

Name Type Required Default Description
formats string No Formats to instruct the controller to provide. Valid values are html (the default), xml, json, csv, pdf, and xls.
provides("html,xml,json");

put()

Configuration Routing struct mapper

Create a route that matches a URL requiring an HTTP PUT method. We recommend using this matcher to expose actions that update database records. This method is provided as a convenience for when you really need to support the PUT verb; consider using the patch matcher instead of this one.

Name Type Required Default Description
name string No Camel-case name of route to reference when build links and form actions (e.g., blogPost).
pattern string No Overrides the URL pattern that will match the route. The default value is a dasherized version of name (e.g., a name of blogPost generates a pattern of blog-post).
to string No Set controller##action combination to map the route to. You may use either this argument or a combination of controller and action.
controller string No Map the route to a given controller. This must be passed along with the action argument.
action string No Map the route to a given action within the controller. This must be passed along with the controller argument.
package string No Indicates a subfolder that the controller will be referenced from (but not added to the URL pattern). For example, if you set this to admin, the controller will be located at admin/YourController.cfc, but the URL path will not contain admin/.
on string No If this route is within a nested resource, you can set this argument to member or collection. A member route contains a reference to the resource's key, while a collection route does not.
redirect string No Redirect via 302 to this URL when this route is matched. Has precedence over controller/action. Use either an absolute link like /about/, or a full canonical link.
<cfscript>

mapper()
    // Route name:  ghostStory
    // Example URL: /ghosts/666/stories/616
    // Controller:  Stories
    // Action:      update
    .put(name="ghostStory", pattern="ghosts/[ghostKey]/stories/[key]", to="stories##update")

    // Route name:  goblins
    // Example URL: /goblins
    // Controller:  Goblins
    // Action:      update
    .put(name="goblins", controller="goblins", action="update")

    // Route name:  heartbeat
    // Example URL: /heartbeat
    // Controller:  Sessions
    // Action:      update
    .put(name="heartbeat", to="sessions##update")

    // Route name:  usersPreferences
    // Example URL: /preferences
    // Controller:  users.Preferences
    // Action:      update
    .put(name="preferences", to="preferences##update", package="users")

    // Route name:  orderShipment
    // Example URL: /shipments/5432
    // Controller:  orders.Shipments
    // Action:      update
    .put(
        name="shipment",
        pattern="shipments/[key]",
        to="shipments##update",
        package="orders"
    )

    // Example scoping within a nested resource
    .resources(name="subscribers", nested=true)
        // Route name:  launchSubscribers
        // Example URL: /subscribers/3209/launch
        // Controller:  Subscribers
        // Action:      launch
        .put(name="launch", to="subscribers##update", on="collection")

        // Route name:  discontinueSubscriber
        // Example URL: /subscribers/2251/discontinue
        // Controller:  Subscribers
        // Action:      discontinue
        .put(name="discontinue", to="subscribers##discontinue", on="member")
    .end()
.end();

</cfscript>

radioButton()

View Helpers Form Object Functions string controller

Builds and returns a string containing a radio button form control based on the supplied objectName and property. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
objectName any Yes The variable name of the object to build the form control for.
property string Yes The name of the property to use in the form control.
association string No The name of the association that the property is located on. Used for building nested forms that work with nested properties. If you are building a form with deep nesting, simply pass in a list to the nested object, and CFWheels will figure it out.
position string No The position used when referencing a hasMany relationship in the association argument. Used for building nested forms that work with nested properties. If you are building a form with deep nestings, simply pass in a list of positions, and CFWheels will figure it out.
tagValue string No The value of the radio button when selected.
label string No useDefaultLabel The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
errorElement string No span HTML tag to wrap the form control with when the object contains errors.
errorClass string No field-with-errors The class name of the HTML tag that wraps the form control when there are errors.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
// Basic example view code.
<cfoutput>
	<fieldset>
		<legend>Gender</legend>
			#radioButton(objectName="user", property="gender", tagValue="m", label="Male")#<br>
			#radioButton(objectName="user", property="gender", tagValue="f", label="Female")#
	</fieldset>
</cfoutput>

// Shows radio buttons for selecting the genders for all committee members provided by the `members` association and nested properties.
<cfoutput>
	<cfloop from="1" to="#ArrayLen(committee.members)#" index="i">
		<div>
			<h3>#committee.members[i].fullName#:</h3>
			<div>
				#radioButton(objectName="committee", association="members", position=i, property="gender", tagValue="m", label="Male")#<br>
				#radioButton(objectName="committee", association="members", position=i, property="gender", tagValue="f", label="Female")#
			</div>
		</div>
	</cfloop>
</cfoutput>

radioButtonTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing a radio button form control based on the supplied name. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
value string Yes Value to populate in tag's value attribute.
checked boolean No false Whether or not to check the radio button by default.
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
// Basic usage usually involves a `label`, `name`, `value`, and `checked` value 
<cfoutput>
	<fieldset>
		<legend>Gender</legend>
		#radioButtonTag(name="gender", value="m", label="Male", checked=true)#<br>
		#radioButtonTag(name="gender", value="f", label="Female")#
	</fieldset>
</cfoutput>

redirectTo()

Controller Miscellaneous Functions void controller

Redirects the browser to the supplied controller/action/key, route or back to the referring page. Internally, this function uses the URLFor function to build the link and the cflocation tag to perform the redirect.

Name Type Required Default Description
back boolean No false Set to true to redirect back to the referring page.
addToken boolean No false See documentation for your CFML engine's implementation of cflocation.
statusCode numeric No 302 See documentation for your CFML engine's implementation of cflocation.
route string No Name of a route that you have configured in config/routes.cfm.
method string No
controller string No Name of the controller to include in the URL.
action string No Name of the action to include in the URL.
key any No Key(s) to include in the URL.
params string No Any additional parameters to be set in the query string (example: wheels=cool&x=y). Please note that CFWheels uses the & and = characters to split the parameters and encode them properly for you. However, if you need to pass in & or = as part of the value, then you need to encode them (and only them), example: a=cats%26dogs%3Dtrouble!&b=1.
anchor string No Sets an anchor name to be appended to the path.
onlyPath boolean No true If true, returns only the relative URL (no protocol, host name or port).
host string No Set this to override the current host.
protocol string No Set this to override the current protocol.
port numeric No 0 Set this to override the current port number.
url string No Redirect to an external URL.
delay boolean No false Set to true to delay the redirection until after the rest of your action code has executed.
encode boolean No true Encode URL parameters using EncodeForURL(). Please note that this does not make the string safe for placement in HTML attributes, for that you need to wrap the result in EncodeForHtmlAttribute() or use linkTo(), startFormTag() etc instead.
// Redirect to an action after successfully saving a user.
if (user.save()) {
	redirectTo(action="saveSuccessful");
}

// Redirect to a specific page on a secure server.
redirectTo(controller="checkout", action="start", params="type=express", protocol="https");

// Redirect to a route specified in `config/routes.cfm` and pass in the screen name that the route takes.
redirectTo(route="profile", screenName="Joe");

// Redirect back to the page the user came from.
redirectTo(back=true);

redoMigration()

Migrator General Functions string migrator

Reruns the specified migration version. Whilst you can use this in your application, the recommended useage is via either the CLI or the provided GUI interface

Name Type Required Default Description
version string No The Database schema version to rerun

references()

Migrator Table Definition Functions any tabledefinition

adds integer reference columns to table definition and creates foreign key constraints

Name Type Required Default Description
referenceNames string Yes
default string No
null boolean No false
polymorphic boolean No false
foreignKey boolean No true
onUpdate string No
onDelete string No

reload()

Model Object Miscellaneous Functions void model

Reloads the property values of this object from the database.

// Get an object, call a method on it that could potentially change values, and then reload the values from the database
employee = model("employee").findByKey(params.key);
employee.someCallThatChangesValuesInTheDatabase();
employee.reload();

removeColumn()

Migrator Migration Functions void migration

Removes a column from a database table Only available in a migration CFC

Name Type Required Default Description
table string Yes The table containing the column to remove
columnName string No The column name to remove
referenceName string No optional reference name

removeIndex()

Migrator Migration Functions void migration

Remove a database index Only available in a migration CFC

Name Type Required Default Description
table string Yes The table name to perform the index operation on
indexName string Yes the name of the index to remove
removeIndex(table='members',indexName='members_username');

removeRecord()

Migrator Migration Functions void migration

Removes existing records from a table Only available in a migration CFC

Name Type Required Default Description
table string Yes The table name to remove the record from
where string No The where clause, i.e id = 123

renameColumn()

Migrator Migration Functions void migration

Renames a table column Only available in a migration CFC

Name Type Required Default Description
table string Yes The table containing the column to rename
columnName string Yes The column name to rename
newColumnName string Yes The new column name

renameTable()

Migrator Migration Functions void migration

Renames a table Only available in a migration CFC

Name Type Required Default Description
oldName string Yes Name the old table
newName string Yes New name for the table

renderNothing()

Controller Rendering Functions void controller

Instructs the controller to render an empty string when it's finished processing the action. This is very similar to calling cfabort with the advantage that any after filters you have set on the action will still be run.

Name Type Required Default Description
status string No [runtime expression] Force request to return with specific HTTP status code.
// Render a blank white page to the client
renderNothing();

renderPartial()

Controller Rendering Functions any controller

Instructs the controller to render a partial when it's finished processing the action.

Name Type Required Default Description
partial string Yes The name of the partial file to be used. Prefix with a leading slash (/) if you need to build a path from the root views folder. Do not include the partial filename's underscore and file extension.
cache any No Number of minutes to cache the content for.
layout string No The layout to wrap the content in. Prefix with a leading slash (/) if you need to build a path from the root views folder. Pass false to not load a layout at all.
returnAs string No Set to string to return the result instead of automatically sending it to the client.
dataFunction any No true Name of a controller function to load data from.
status string No [runtime expression] Force request to return with specific HTTP status code.
// Render the partial `_comment.cfm` located in the current controller's view folder
renderPartial("comment");

// Render the partial at `views/shared/_comment.cfm`
renderPartial("/shared/comment");

renderText()

Controller Rendering Functions void controller

Instructs the controller to render specified text when it's finished processing the action.

Name Type Required Default Description
text string No The text to render.
status any No [runtime expression] Force request to return with specific HTTP status code.
// Render just the text "Done!" to the client
renderText("Done!");

// Render serialized product data to the client
products = model("product").findAll();
renderText(SerializeJson(products));

renderView()

Controller Rendering Functions any controller

Instructs the controller which view template and layout to render when it's finished processing the action. Note that when passing values for controller and / or action, this function does not execute the actual action but rather just loads the corresponding view template.

Name Type Required Default Description
controller string No [runtime expression] Controller to include the view page for.
action string No [runtime expression] Action to include the view page for.
template string No A specific template to render. Prefix with a leading slash (/) if you need to build a path from the root views folder.
layout any No The layout to wrap the content in. Prefix with a leading slash (/) if you need to build a path from the root views folder. Pass false to not load a layout at all.
cache any No Number of minutes to cache the content for.
returnAs string No Set to string to return the result instead of automatically sending it to the client.
hideDebugInformation boolean No false Set to true to hide the debug information at the end of the output. This is useful, for example, when you're testing XML output in an environment where the global setting for showDebugInformation is true.
status string No [runtime expression] Force request to return with specific HTTP status code.
// Render a view page for a different action within the same controller.
renderView(action="edit");

// Render a view page for a different action within a different controller.
renderView(controller="blog", action="new");

// Another way to render the blog/new template from within a different controller.
renderView(template="/blog/new");

// Render the view page for the current action but without a layout and cache it for 60 minutes.
renderView(layout=false, cache=60);

// Load a layout from a different folder within `views`.
renderView(layout="/layouts/blog");

// Don't render the view immediately but rather return and store in a variable for further processing.
myView = renderView(returnAs="string");

renderWith()

Controller Rendering Functions any controller

Instructs the controller to render the data passed in to the format that is requested. If the format requested is json or xml, CFWheels will transform the data into that format automatically. For other formats (or to override the automatic formatting), you can also create a view template in this format: nameofaction.xml.cfm, nameofaction.json.cfm, nameofaction.pdf.cfm, etc.

Name Type Required Default Description
data any Yes Data to format and render.
controller string No [runtime expression] Controller to include the view page for.
action string No [runtime expression] Action to include the view page for.
template string No A specific template to render. Prefix with a leading slash (/) if you need to build a path from the root views folder.
layout any No The layout to wrap the content in. Prefix with a leading slash (/) if you need to build a path from the root views folder. Pass false to not load a layout at all.
cache any No Number of minutes to cache the content for.
returnAs string No Set to string to return the result instead of automatically sending it to the client.
hideDebugInformation boolean No false Set to true to hide the debug information at the end of the output. This is useful, for example, when you're testing XML output in an environment where the global setting for showDebugInformation is true.
status string No [runtime expression] Force request to return with specific HTTP status code.
// This will provide the formats defined in the `config()` function.
products = model("product").findAll();
renderWith(products);

// Provide a 403 status code for a json response (for example)
msg={
	"status" : "Error",
	"message": "Not Authenticated"
}
renderWith(data=msg, status=403)

resetCycle()

View Helpers Miscellaneous Functions void controller

Resets a cycle so that it starts from the first list value the next time it is called.

Name Type Required Default Description
name string No default The name of the cycle to reset.
// alternating row colors and shrinking emphasis
<cfoutput query="employees" group="departmentId">
	<div class="#cycle(values="even,odd", name="row")#">
		<ul>
			<cfoutput>
				rank = cycle(values="president,vice-president,director,manager,specialist,intern", name="position")>
				<li class="#rank#">#categories.categoryName#</li>
				resetCycle("emphasis")>
			</cfoutput>
		</ul>
	</div>
</cfoutput>

resource()

Configuration Routing struct mapper

Create a group of routes that exposes actions for manipulating a singular resource. A singular resource exposes URL patterns for the entire CRUD lifecycle of a single entity (show, new, create, edit, update, and delete) without exposing a primary key in the URL. Usually this type of resource represents a singleton entity tied to the session, application, or another resource (perhaps nested within another resource). If you need to generate routes for manipulating a collection of resources with a primary key in the URL, see the resources mapper method.

Name Type Required Default Description
name string Yes Camel-case name of resource to reference when build links and form actions. This is typically a singular word (e.g., profile).
nested boolean No false Whether or not additional calls will be nested within this resource.
path string No [runtime expression] Override URL path representing this resource. Default is a dasherized version of name (e.g., blogPost generates a path of blog-post).
controller string No Override name of the controller used by resource. This defaults to a pluralized version of name.
singular string No Override singularize() result in plural resources.
plural string No Override pluralize() result in singular resource.
only string No Limits the list of RESTful routes to generate. Can include show, new, create, edit, update, and delete.
except string No Excludes RESTful routes to generate, taking priority over the only argument. Can include show, new, create, edit, update, and delete.
shallow boolean No Turn on shallow resources.
shallowPath string No Shallow path prefix.
shallowName string No Shallow name prefix.
constraints struct No Variable patterns to use for matching.
mapFormat boolean No [runtime expression] Whether or not to add an optional .[format] pattern to the end of the generated routes. This is useful for providing formats via URL like json, xml, pdf, etc.
<cfscript>

mapper()
    // With default arguments
    .resource("checkout")

    // Point auth URL to controller at `controllers/sessions/Auth.cfc`
    .resource(name="auth", controller="sessions.auth")

    // Limited list of routes generated by `only` argument.
    .resource(name="profile", only="show,edit,update")

    // Limited list of routes generated by `except` argument.
    .resource(name="cart", except="new,create,edit,delete")

    // Nested resource
    .resource(name="preferences", only="index", nested=true)
      .get(name="editPassword", to="passwords##edit")
      .patch(name="password", to="passwords##update")

      .resources("foods")
    .end()

    // Overridden `path`
    .resource(name="blogPostOptions", path="blog-post/options")
.end();

</cfscript>

resources()

Configuration Routing struct mapper

Create a group of routes that exposes actions for manipulating a collection of resources. A plural resource exposes URL patterns for the entire CRUD lifecycle (index, show, new, create, edit, update, delete), exposing a primary key in the URL for showing, editing, updating, and deleting records. If you need to generate routes for manipulating a singular resource without a primary key, see the resource mapper method.

Name Type Required Default Description
name string Yes Camel-case name of resource to reference when build links and form actions. This is typically a plural word (e.g., posts).
nested boolean No false Whether or not additional calls will be nested within this resource.
path string No [runtime expression] Override URL path representing this resource. Default is a dasherized version of name (e.g., blogPosts generates a path of blog-posts).
controller string No Override name of the controller used by resource. This defaults to the value provided for name.
singular string No Override singularize() result in plural resources.
plural string No Override pluralize() result in singular resource.
only string No Limits the list of RESTful routes to generate. Can include index, show, new, create, edit, update, and delete.
except string No Excludes RESTful routes to generate, taking priority over the only argument. Can include index, show, new, create, edit, update, and delete.
shallow boolean No Turn on shallow resources.
shallowPath string No Shallow path prefix.
shallowName string No Shallow name prefix.
constraints struct No Variable patterns to use for matching.
mapFormat boolean No [runtime expression] Whether or not to add an optional .[format] pattern to the end of the generated routes. This is useful for providing formats via URL like json, xml, pdf, etc.
<cfscript>

mapper()
    // With default arguments
    .resources("admins")

    // Point authors URL to controller at `controllers/Users.cfc`
    .resources(name="authors", controller="users")

    // Limited list of routes generated by `only` argument.
    .resources(name="products", only="index,show,edit,update")

    // Limited list of routes generated by `except` argument.
    .resources(name="orders", except="delete")

    // Nested resources
    .resources(name="stories", nested=true)
      .resources("heroes")
      .resources("villains")
    .end()

    // Overridden `path`
    .resources(name="blogPostsOptions", path="blog-posts/options")
.end();

</cfscript>

response()

Controller Rendering Functions string controller

Returns content that CFWheels will send to the client in response to the request.

wheelsResponse = response();

root()

Configuration Routing struct mapper

Create a route that matches the root of its current context. This mapper can be used for the application's web root (or home page), or it can generate a route for the root of a namespace or other path scoping mapper.

Name Type Required Default Description
to string No Set controller##action combination to map the route to. You may use either this argument or a combination of controller and action.
mapFormat boolean No Set to true to include the format (e.g. .json) in the route.
<cfscript>

mapper()
    .namespace("api")
        // Map the root of the `api` folder to the `index` action of the `apis`
        // controller.
        .root(controller="apis", action="index")
    .end()

    // Map the root of the application to the `show` action of the `dashboards`
    // controller.
    .root(to="dashboards##show")
.end();

</cfscript>

save()

Model Class CRUD Functions boolean model

Saves the object if it passes validation and callbacks. Returns true if the object was saved successfully to the database, false if not.

Name Type Required Default Description
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
reload boolean No false Set to true to force CFWheels to query the database even though an identical query for this model may have been run in the same request. (The default in CFWheels is to get the second query from the model's request-level cache.)
validate boolean No true Set to false to skip validations for this operation.
transaction string No [runtime expression] Set this to commit to update the database, rollback to run all the database queries but not commit them, or none to skip transaction handling altogether.
callbacks boolean No true Set to false to disable callbacks for this method.
allowExplicitTimestamps boolean No false Set this to true to allow explicit assignment of createdAt or updatedAt properties
// Save the user object to the database (will automatically do an `INSERT` or `UPDATE` statement depending on if the record is new or already exists
user.save();

// Save the user object directly in an if statement without using `cfqueryparam` and take appropriate action based on the result
if(user.save(parameterize=false)){
	flashInsert(notice="The user was saved!");
	redirectTo(action="edit");
} else {
	flashInsert(alert="Error, please correct!");
	renderView(action="edit");
}

scope()

Configuration Routing struct mapper

Set any number of parameters to be inherited by mappers called within this matcher's block. For example, set a package or URL path to be used by all child routes.

Name Type Required Default Description
name string No Name to prepend to child route names for use when building links, forms, and other URLs.
path string No Path to prefix to all child routes.
package string No Package namespace to append to controllers.
controller string No Controller to use for routes.
shallow boolean No Turn on shallow resources to eliminate routing added before this one.
shallowPath string No Shallow path prefix.
shallowName string No Shallow name prefix.
constraints struct No Variable patterns to use for matching.
<cfscript>

mapper()
    // All routes inside will use the `freeForAll` controller.
    .scope(controller="freeForAll")
        .get(name="bananas", action="bananas")
        .root(action="index")
    .end()

    // All routes's controllers inside will be inside the `public` package/subfolder.
    .scope(package="public")
        .resource(name="search", only="show,create")
    .end()

    // All routes inside will be prepended with a URL path of `phones/`.
    .scope(path="phones")
        .get(name="newest", to="phones##newest")
        .get(name="sortOfNew", to="phones##sortOfNew")
    .end()
.end();

</cfscript>

secondSelectTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing one select form control for the seconds of a minute based on the supplied name.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
selected string No The day that should be selected initially.
secondStep numeric No 1 Pass in 10 to only show seconds 10, 20, 30, etc.
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- This "Tag" version of the function accepts a `name` and `selected` instead of binding to a model object --->
#secondSelectTag(name="secondsToLaunch", selected=params.secondsToLaunch)#
</cfoutput>

<!--- Only show 15-second intervals --->
#secondSelectTag(name="secondsToLaunch", value=params.secondsToLaunch, secondStep=15)# 

select()

View Helpers Form Object Functions string controller

Builds and returns a string containing a select form control based on the supplied objectName and property. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
objectName any Yes The variable name of the object to build the form control for.
property string Yes The name of the property to use in the form control.
association string No The name of the association that the property is located on. Used for building nested forms that work with nested properties. If you are building a form with deep nesting, simply pass in a list to the nested object, and CFWheels will figure it out.
position string No The position used when referencing a hasMany relationship in the association argument. Used for building nested forms that work with nested properties. If you are building a form with deep nestings, simply pass in a list of positions, and CFWheels will figure it out.
options any No A collection to populate the select form control with. Can be a query recordset or an array of objects.
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
valueField string No The column or property to use for the value of each list element. Used only when a query or array of objects has been supplied in the options argument. Required when specifying textField
textField string No The column or property to use for the value of each list element that the end user will see. Used only when a query or array of objects has been supplied in the options argument. Required when specifying valueField
label string No useDefaultLabel The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
errorElement string No span HTML tag to wrap the form control with when the object contains errors.
errorClass string No field-with-errors The class name of the HTML tag that wraps the form control when there are errors.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
// Example 1: Basic `select` field with `label` and required `objectName` and `property` arguments
// - Controller code
authors = model("author").findAll();

<!--- View code--->
#select(objectName="book", property="authorId", options=authors)#

<!---
	Do this when CFWheels isn't grabbing the correct values for the `option`s' values and display texts
	Note that `valueField` and `textField` are both required when using this option
--->
#select(objectName="book", property="authorId", options=authors, valueField="id", textField="authorfullname")#

// Example 2: Shows `select` fields for selecting order statuses for all shipments provided by the `orders` association and nested properties
// Controller code
shipment = model("shipment").findByKey(key=params.key, where="shipments.statusId=#application.NEW_STATUS_ID#", include="order");
statuses = model("status").findAll(order="name");

<!--- View code--->
<cfloop from="1" to="#ArrayLen(shipments.orders)#" index="i">
	#select(label="Order #shipments.orders[i].orderNum#", objectName="shipment", association="orders", position=i, property="statusId", options=statuses)#
</cfloop>

selectTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing a select form control based on the supplied name and options. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
options any Yes A collection to populate the select form control with. Can be a query recordset or an array of objects.
selected string No Value of option that should be selected by default.
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
multiple boolean No false Whether to allow multiple selection of options in the select form control.
valueField string No The column or property to use for the value of each list element. Used only when a query or array of objects has been supplied in the options argument. Required when specifying textField
textField string No The column or property to use for the value of each list element that the end user will see. Used only when a query or array of objects has been supplied in the options argument. Required when specifying valueField
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
// Controller code
cities = model("city").findAll()>

<!--- View code--->
#selectTag(name="cityId", options=cities)#

<!---
	Do this when CFWheels isn't grabbing the correct values for the `option`s' values and display texts
	Note that `valueField` and `textField` are both required when using this option
--->
#selectTag(name="cityId", options=cities, valueField="id", textField="name")#

sendEmail()

Controller Miscellaneous Functions any controller

Sends an email using a template and an optional layout to wrap it in. Besides the CFWheels-specific arguments documented here, you can also pass in any argument that is accepted by the cfmail tag as well as your own arguments to be used by the view.

Name Type Required Default Description
template string No The path to the email template or two paths if you want to send a multipart email. if the detectMultipart argument is false, the template for the text version should be the first one in the list. This argument is also aliased as templates.
from string No Email address to send from.
to string No List of email addresses to send the email to.
subject string No The subject line of the email.
layout any No false Layout(s) to wrap the email template in. This argument is also aliased as layouts.
file string No A list of the names of the files to attach to the email. This will reference files stored in the files folder (or a path relative to it). This argument is also aliased as files.
detectMultipart boolean No true When set to true and multiple values are provided for the template argument, CFWheels will detect which of the templates is text and which one is HTML (by counting the < characters).
deliver boolean No true When set to false, the email will not be sent.
writeToFile string No The file to which the email contents will be written
// Get a member and send a welcome email, passing in a few custom variables to the template
newMember = model("member").findByKey(params.member.id);
sendEmail(
	to=newMember.email,
	template="myemailtemplate",
	subject="Thank You for Becoming a Member",
	recipientName=newMember.name,
	startDate=newMember.startDate
);

sendFile()

Controller Miscellaneous Functions any controller

Sends a file to the user (from the files folder or a path relative to it by default).

Name Type Required Default Description
file string Yes The file to send to the user.
name string No The file name to show in the browser download dialog box.
type string No The HTTP content type to deliver the file as.
disposition string No attachment Set to inline to have the browser handle the opening of the file (possibly inline in the browser) or set to attachment to force a download dialog box.
directory string No Directory outside of the web root where the file exists. Must be a full path.
deleteFile boolean No false Pass in true to delete the file on the server after sending it.
deliver boolean No true
// Send a PDF file to the user
sendFile(file="wheels_tutorial_20081028_J657D6HX.pdf");

// Send the same file but give the user a different name in the browser dialog window
sendFile(file="wheels_tutorial_20081028_J657D6HX.pdf", name="Tutorial.pdf");

// Send a file that is located outside of the web root
sendFile(file="../../tutorials/wheels_tutorial_20081028_J657D6HX.pdf");

// Send a file that is located in ram://
sendFile(file="ram://wheels_tutorial_20081028_J657D6HX.pdf");

set()

Configuration Miscellaneous Functions void controller model migrator migration tabledefinition

Use to configure a global setting or set a default for a function.

// Example 1: Set the `URLRewriting` setting to `Partial`.
set(URLRewriting="Partial");

// Example 2: Set default values for the arguments in the `buttonTo` view helper. This works for the majority of Wheels functions/arguments.
set(functionName="buttonTo", onlyPath=true, host="", protocol="", port=0, text="", confirm="", image="", disable="");

// Example 3: Set the default values for a form helper to get the form marked up to your preferences.
set(functionName="textField", labelPlacement="before", prependToLabel="<div>", append="</div>", appendToLabel="<br>"):

setFilterChain()

Controller Configuration Functions void controller

Use this function if you need a more low level way of setting the entire filter chain for a controller.

Name Type Required Default Description
chain array Yes An array of structs, each of which represent an argumentCollection that get passed to the filters function. This should represent the entire filter chain that you want to use for this controller.
// Set filter chain directly in an array.
setFilterChain([
	{through="restrictAccess"},
	{through="isLoggedIn, checkIPAddress", except="home, login"},
	{type="after", through="logConversion", only="thankYou"}
]);

setPagination()

Controller Pagination Functions void controller model migrator migration tabledefinition

Allows you to set a pagination handle for a custom query so you can perform pagination on it in your view with paginationLinks.

Name Type Required Default Description
totalRecords numeric Yes Total count of records that should be represented by the paginated links.
currentPage numeric No 1 Page number that should be represented by the data being fetched and the paginated links.
perPage numeric No 25 Number of records that should be represented on each page of data.
handle string No query Name of handle to reference in paginationLinks.
/* Note that there are two ways to do pagination yourself using a custom query.
	1) Do a query that grabs everything that matches and then use
	the `cfouput` or `cfloop` tag to page through the results.
	2) Use your database to make 2 queries. The first query
	basically does a count of the total number of records that match
	the criteria and the second query actually selects the page of
	records for retrieval.
	In the example below, we will show how to write a custom query
	using both of these methods. Note that the syntax where your
	database performs the pagination will differ depending on the
	database engine you are using. Plese consult your database
	engine's documentation for the correct syntax.
	Also note that the view code will differ depending on the method
	used.
*/

//=================== First method: Handle the pagination through your CFML engine

// Model code: In your model (ie. User.cfc), create a custom method for your custom query
function myCustomQuery(required numeric page, numeric perPage=25){
	local.customQuery=QueryExecute("SELECT * FROM users", [], { datasource=get('dataSourceName') });
	setPagination(
		totalRecords=local.customQuery.RecordCount,
		currentPage=arguments.page,
		perPage=arguments.perPage,
		handle="myCustomQueryHandle");
	return local.customQuery;
}

// Controller code
function list(){
	param name="params.page" default="1;
	param name="params.perPage" default="25";
	allUsers = model("user").myCustomQuery( page=params.page, perPage=params.perPage);

	// Because we're going to let `cfoutput`/`cfloop` handle the pagination,
	// we're going to need to get some addition information about the pagination.
	paginationData = pagination("myCustomQueryHandle")
}

<!--- View code (using `cfloop`): Use the information from `paginationData` to page through the records --->
<ul>
	<cfloop query="allUsers" startrow="#paginationData.startrow#" endrow="#paginationData.endrow#" >
	<li> #allUsers.firstName# #allUsers.lastName# </li>
	</cfloop>
</ul>
#paginationLinks(handle="myCustomQueryHandle")#

<!--- View code (using `cfoutput`) Use the information from `paginationData` to page through the records--->
<ul>
	<cfoutput query="allUsers" startrow="#paginationData.startrow#" maxrows="#paginationData.maxrows#" >
	<li> #allUsers.firstName# #allUsers.lastName# </li>
	</cfoutput>
</ul>
#paginationLinks(handle="myCustomQueryHandle")#

//=================== Second method: Handle the pagination through the database

// Model code: In your model (ie. `User.cfc`), create a custom method for your custom query

function myCustomQuery(required numeric page, numeric perPage=25){
	local.customQueryCount=QueryExecute("SELECT COUNT(*) AS theCount FROM users",
										[], { datasource=get('dataSourceName') });
	local.customQuery=QueryExecute("SELECT * FROM users LIMIT ? OFFSET ?",
									[arguments.page, arguments.perPage],
									{ datasource=get('dataSourceName') });

	//Notice the we use the value from the first query for `totalRecords`
	setPagination(
		totalRecords=local.customQueryCount.theCount,
		currentPage=arguments.page,
		perPage=arguments.perPage,
		handle="myCustomQueryHandle" );

	// We return the second query
	return local.customQuery;
}

// Controller code
function list(){
	param name="params.page" default="1;
	param name="params.perPage" default="25";
	allUsers = model("user").myCustomQuery( page=params.page, perPage=params.perPage);
}

<!--- View code (using `cfloop`)--->
<ul>
	<cfloop query="allUsers">
	<li> #allUsers.firstName# #allUsers.lastName# </li>
	</cfloop>
</ul>
#paginationLinks(handle="myCustomQueryHandle")#

<!--- View code (using `cfoutput`)--->
<ul>
	<cfoutput query="allUsers">
	<li> #allUsers.firstName# #allUsers.lastName# </li>
	</cfoutput>
</ul>
#paginationLinks(handle="myCustomQueryHandle")#

setPrimaryKey()

Model Configuration Miscellaneous Functions void model

Allows you to pass in the name(s) of the property(s) that should be used as the primary key(s). Pass as a list if defining a composite primary key. This function is also aliased as setPrimaryKeys().

Name Type Required Default Description
property string Yes Property (or list of properties) to set as the primary key.
// In `models/User.cfc`, define the primary key as a column called `userID`.
function config(){
	setPrimaryKey("userID");
}

setPrimaryKeys()

Model Configuration Miscellaneous Functions void model

Alias for setPrimaryKey(). Use this for better readability when you're setting multiple properties as the primary key.

Name Type Required Default Description
property string Yes Property (or list of properties) to set as the primary key.
// In `models/Subscription.cfc`, define the primary key as composite of the columns `customerId` and `publicationId`.
function config(){
	setPrimaryKeys("customerId,publicationId");
}

setProperties()

Model Object Miscellaneous Functions void model

Allows you to set all the properties of an object at once by passing in a structure with keys matching the property names.

Name Type Required Default Description
properties struct No [runtime expression] The properties you want to set on the object (can also be passed in as named arguments).
// Update the properties of the object with the params struct containing the values of a form post
user = model("user").findByKey(1);
user.setProperties(params.user);

setResponse()

Controller Rendering Functions void controller

Sets content that CFWheels will send to the client in response to the request.

Name Type Required Default Description
content string Yes The content to send to the client.
setResponse(newReponse);

setTableNamePrefix()

Model Configuration Miscellaneous Functions void model

Sets a prefix to prepend to the table name when this model runs SQL queries.

Name Type Required Default Description
prefix string Yes A prefix to prepend to the table name.
// In `models/User.cfc`, add a prefix to the default table name of `tbl`.
function config(){
	setTableNamePrefix("tbl");
}

setVerificationChain()

Controller Configuration Functions void controller

Use this function if you need a more low level way of setting the entire verification chain for a controller.

Name Type Required Default Description
chain array Yes An array of structs, each of which represent an argumentCollection that get passed to the verifies function. This should represent the entire verification chain that you want to use for this controller.
// Set verification chain directly in an array.
setVerificationChain([
	{only="handleForm", post=true},
	{only="edit", get=true, params="userId", paramsTypes="integer"},
	{only="edit", get=true, params="userId", paramsTypes="integer", handler="index", error="Invalid userId"}
]);

simpleFormat()

View Helpers Miscellaneous Functions string controller

Returns formatted text using HTML break tags (
) and HTML paragraph elements (

) based on the newline characters and carriage returns in the text that is passed in.

Name Type Required Default Description
text string Yes The text to format.
wrap boolean No true Set to true to wrap the result in a paragraph HTML element.
encode boolean No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- How most of your calls will look. --->
#simpleFormat(post.bodyText)#

<!--- Demonstrates what output looks like with specific data. --->
<cfsavecontent variable="comment">
	I love this post!

	Here's why:
	* Short
	* Succinct
	* Awesome
</cfsavecontent>
#simpleFormat(comment)#

<!---
	<p>I love this post!</p>

	<p>Here's why:<br>
	* Short<br>
	* Succinct<br>
	* Awesome</p>
--->

singularize()

Global Helpers String Functions string controller model mapper migrator migration tabledefinition

Returns the singular form of the passed in word.

Name Type Required Default Description
word string Yes
// Singularize a word, will result in "language" 
#singularize("languages")#

startFormTag()

View Helpers General Form Functions string controller

Builds and returns a string containing the opening form tag. The form's action will be built according to the same rules as URLFor. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
method string No post The type of method to use in the form tag (delete, get, patch, post, and put are the options).
multipart boolean No false Set to true if the form should be able to upload files.
route string No Name of a route that you have configured in config/routes.cfm.
controller string No Name of the controller to include in the URL.
action string No Name of the action to include in the URL.
key any No Key(s) to include in the URL.
params string No Any additional parameters to be set in the query string (example: wheels=cool&x=y). Please note that CFWheels uses the & and = characters to split the parameters and encode them properly for you. However, if you need to pass in & or = as part of the value, then you need to encode them (and only them), example: a=cats%26dogs%3Dtrouble!&b=1.
anchor string No Sets an anchor name to be appended to the path.
onlyPath boolean No true If true, returns only the relative URL (no protocol, host name or port).
host string No Set this to override the current host.
protocol string No Set this to override the current protocol.
port numeric No 0 Set this to override the current port number.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- View Code --->
#startFormTag(action="create")#
    <!--- your form controls --->
#endFormTag()#

string()

Migrator Table Definition Functions any tabledefinition

adds string columns to table definition

Name Type Required Default Description
columnNames string No
limit any No
default string No
null boolean No

stripTags()

View Helpers Sanitization Functions string controller

Removes all HTML tags from a string.

Name Type Required Default Description
html string Yes The HTML to remove tag markup from.
encode boolean No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- Will output: CFWheels is a framework for ColdFusion. --->
#stripTags('<strong>Wheels</strong> is a framework for <a href="http://www.adobe.com/products/coldfusion">ColdFusion</a>.')#

styleSheetLinkTag()

View Helpers Asset Functions string controller

Returns a link tag for a stylesheet (or several) based on the supplied arguments.

Name Type Required Default Description
sources string No The name of one or many CSS files in the stylesheets folder, minus the .css extension. Pass a full URL to generate a tag for an external style sheet. Can also be called with the source argument.
type string No text/css The type attribute for the link tag.
media string No all The media attribute for the link tag.
rel string No The rel attribute for the relation between the tag and href.
head boolean No false Set to true to place the output in the head area of the HTML page instead of the default behavior (which is to place the output where the function is called from).
delim string No , The delimiter to use for the list of CSS files.
encode boolean No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- view code --->
<head>
    <!--- Includes `stylesheets/styles.css` --->
    #styleSheetLinkTag("styles")#
    <!--- Includes `stylesheets/blog.css` and `stylesheets/comments.css` --->
    #styleSheetLinkTag("blog,comments")#
    <!--- Includes printer style sheet --->
    #styleSheetLinkTag(sources="print", media="print")#
    <!--- Includes external style sheet --->
    #styleSheetLinkTag("http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.0/themes/cupertino/jquery-ui.css")#
</head>

<body>
    <!--- This will still appear in the `head` --->
    #styleSheetLinkTag(sources="tabs", head=true)#
</body>

submitTag()

View Helpers General Form Functions string controller

Builds and returns a string containing a submit button form control. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
value string No Save changes Message to display in the button form control.
image string No File name of the image file to use in the button form control.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
#startFormTag(action="something")#
    <!--- form controls go here --->
    #submitTag()#
#endFormTag()#

sum()

Model Class Statistics Functions any model

Calculates the sum of values for a given property. Uses the SQL function SUM. If no records can be found to perform the calculation on you can use the ifNull argument to decide what should be returned.

Name Type Required Default Description
property string Yes Name of the property to get the sum for (must be a property of a numeric data type).
where string No Maps to the WHERE clause of the query (or HAVING when necessary). The following operators are supported: =, !=, <>, <, <=, >, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, and OR (note that the key words need to be written in upper case). You can also use parentheses to group statements. You do not need to specify the table name(s); CFWheels will do that for you.
include string No Associations that should be included in the query using INNER or LEFT OUTER joins (which join type that is used depends on how the association has been set up in your model). If all included associations are set on the current model, you can specify them in a list (e.g. department,addresses,emails). You can build more complex include strings by using parentheses when the association is set on an included model, like album(artist(genre)), for example. These complex include strings only work when returnAs is set to query though.
distinct boolean No false When true, SUM returns the sum of unique values only.
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
ifNull any No The value returned if no records are found. Common usage is to set this to 0 to make sure a numeric value is always returned instead of a blank string.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
group string No Maps to the GROUP BY clause of the query. You do not need to specify the table name(s); CFWheels will do that for you.
// Get the sum of all salaries
allSalaries = model("employee").sum("salary");

// Get the sum of all salaries for employees in a given country
allAustralianSalaries = model("employee").sum(property="salary", include="country", where="countryname='Australia'");

// Make sure a numeric value is always returned, even if there are no records analyzed by the query
salarySum = model("employee").sum(property="salary", where="salary BETWEEN #params.min# AND #params.max#", ifNull=0);

table()

Model Configuration Miscellaneous Functions void model

Use this method to tell CFWheels what database table to connect to for this model. You only need to use this method when your table naming does not follow the standard CFWheels convention of a singular object name mapping to a plural table name. To not use a table for your model at all, call table(false).

Name Type Required Default Description
name any Yes Name of the table to map this model to.
// In models/User.cfc.
function config() {
	// Tell Wheels to use the `tbl_USERS` table in the database for the `user` model instead of the default (which would be `users`).
	table("tbl_USERS");
}

tableName()

Model Class Miscellaneous Functions string model

Returns the name of the database table that this model is mapped to.

// Check what table the user model uses
whatAmIMappedTo = model("user").tableName();

text()

Migrator Table Definition Functions any tabledefinition

adds text columns to table definition

Name Type Required Default Description
columnNames string No
default string No
null boolean No

textArea()

View Helpers Form Object Functions string controller

Builds and returns a string containing a text area field form control based on the supplied objectName and property. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
objectName any Yes The variable name of the object to build the form control for.
property string Yes The name of the property to use in the form control.
association string No The name of the association that the property is located on. Used for building nested forms that work with nested properties. If you are building a form with deep nesting, simply pass in a list to the nested object, and CFWheels will figure it out.
position string No The position used when referencing a hasMany relationship in the association argument. Used for building nested forms that work with nested properties. If you are building a form with deep nestings, simply pass in a list of positions, and CFWheels will figure it out.
label string No useDefaultLabel The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
errorElement string No span HTML tag to wrap the form control with when the object contains errors.
errorClass string No field-with-errors The class name of the HTML tag that wraps the form control when there are errors.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- 	Provide `label` and required `objectName` and `property` --->
#textArea(label="Overview", objectName="article", property="overview")#

<!--- Display fields for photos provided by the `screenshots` association and nested properties --->
<fieldset>
	<legend>Screenshots</legend>
	<cfloop from="1" to="#ArrayLen(site.screenshots)#" index="i">
		#fileField(label="File #i#", objectName="site", association="screenshots", position=i, property="file")#
		#textArea(label="Caption ##i#", objectName="site", association="screenshots", position=i, property="caption")#
	</cfloop>
</fieldset>

textAreaTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing a text area form control based on the supplied name. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
content string No Content to display in textarea on page load.
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- Basic usage usually involves a `label`, `name`, and `password` --->
#textAreaTag(label="Description", name="description", content=params.description)#

textField()

View Helpers Form Object Functions string controller

Builds and returns a string containing a text field form control based on the supplied objectName and property. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
objectName any Yes The variable name of the object to build the form control for.
property string Yes The name of the property to use in the form control.
association string No The name of the association that the property is located on. Used for building nested forms that work with nested properties. If you are building a form with deep nesting, simply pass in a list to the nested object, and CFWheels will figure it out.
position string No The position used when referencing a hasMany relationship in the association argument. Used for building nested forms that work with nested properties. If you are building a form with deep nestings, simply pass in a list of positions, and CFWheels will figure it out.
label string No useDefaultLabel The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
errorElement string No span HTML tag to wrap the form control with when the object contains errors.
errorClass string No field-with-errors The class name of the HTML tag that wraps the form control when there are errors.
type string No text Input type attribute. Common examples in HTML5 and later are text (default), email, tel, and url.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- Provide a `label` and the required `objectName` and `property` --->
#textField(label="First Name", objectName="user", property="firstName")#

<!--- Display fields for phone numbers provided by the `phoneNumbers` association and nested properties --->
<fieldset>
	<legend>Phone Numbers</legend>
	<cfloop from="1" to="#ArrayLen(contact.phoneNumbers)#" index="i">
		#textField(label="Phone ##i#", objectName="contact", association="phoneNumbers", position=i, property="phoneNumber")#
	</cfloop>
</fieldset>

textFieldTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing a text field form control based on the supplied name. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
value string No Value to populate in tag's value attribute.
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
type string No text Input type attribute. Common examples in HTML5 and later are text (default), email, tel, and url.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- Basic usage usually involves a `label`, `name`, and `value` --->
#textFieldTag(label="Search", name="q", value=params.q)#

time()

Migrator Table Definition Functions any tabledefinition

adds time columns to table definition

Name Type Required Default Description
columnNames string No
default string No
null boolean No

timeAgoInWords()

Global Helpers Date Functions any controller model migrator migration tabledefinition

Returns a string describing the approximate time difference between the date passed in and the current date.

Name Type Required Default Description
fromTime date Yes Date to compare from.
includeSeconds boolean No false Whether or not to include the number of seconds in the returned string.
toTime date No [runtime expression] Date to compare to.
// Controller code.
aWhileAgo = DateAdd("d", -90, Now());

// View code.
<!--- Will output: 3 months --->
#timeAgoInWords(aWhileAgo)#

timeSelect()

View Helpers Form Object Functions string controller

Builds and returns a string containing three select form controls for hour, minute, and second based on the supplied objectName and property.

Name Type Required Default Description
objectName any No The variable name of the object to build the form control for.
property string No The name of the property to use in the form control.
association string No The name of the association that the property is located on. Used for building nested forms that work with nested properties. If you are building a form with deep nesting, simply pass in a list to the nested object, and CFWheels will figure it out.
position string No The position used when referencing a hasMany relationship in the association argument. Used for building nested forms that work with nested properties. If you are building a form with deep nestings, simply pass in a list of positions, and CFWheels will figure it out.
order string No hour,minute,second Use to change the order of or exclude time select tags.
separator string No : Use to change the character that is displayed between the time select tags.
minuteStep numeric No 1 Pass in 10 to only show minute 10, 20, 30, etc.
secondStep numeric No 1 Pass in 10 to only show seconds 10, 20, 30, etc.
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
label string No false The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
errorElement string No span HTML tag to wrap the form control with when the object contains errors.
errorClass string No field-with-errors The class name of the HTML tag that wraps the form control when there are errors.
combine boolean No Set to false to not combine the select parts into a single DateTime object.
twelveHour boolean No false whether to display the hours in 24 or 12 hour format. 12 hour format has AM/PM drop downs
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!---View code --->
#timeSelect(objectName="business", property="openUntil")#

<!---Show fields for hour and minute --->
#timeSelect(objectName="business", property="openUntil", order="hour,minute")#

<!---Only show 15-minute intervals --->
#timeSelect(objectName="appointment", property="dateTimeStart", minuteStep=15)#

timeSelectTags()

View Helpers Form Tag Functions string controller

Builds and returns a string containing three select form controls for hour, minute, and second based on name.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
selected string No Value of option that should be selected by default.
order string No hour,minute,second Use to change the order of or exclude time select tags.
separator string No : Use to change the character that is displayed between the time select tags.
minuteStep numeric No 1 Pass in 10 to only show minute 10, 20, 30, etc.
secondStep numeric No 1 Pass in 10 to only show seconds 10, 20, 30, etc.
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
combine boolean No Set to false to not combine the select parts into a single DateTime object.
twelveHour boolean No false whether to display the hours in 24 or 12 hour format. 12 hour format has AM/PM drop downs
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- This "Tag" version of function accepts `name` and `selected` instead of binding to a model object --->
#timeSelectTags(name="timeOfMeeting" selected=params.timeOfMeeting)#

<!--- Show fields for `hour` and `minute` only --->
#timeSelectTags(name="timeOfMeeting", selected=params.timeOfMeeting, order="hour,minute")#

timestamp()

Migrator Table Definition Functions any tabledefinition

adds timestamp columns to table definition

Name Type Required Default Description
columnNames string No
default string No
null boolean No
columnType string No datetime

timestamps()

Migrator Table Definition Functions any tabledefinition

adds CFWheels convention automatic timestamp and soft delete columns to table definition

timeUntilInWords()

Global Helpers Date Functions string controller model migrator migration tabledefinition

Returns a string describing the approximate time difference between the current date and the date passed in.

Name Type Required Default Description
toTime date Yes Date to compare to.
includeSeconds boolean No false Whether or not to include the number of seconds in the returned string.
fromTime date No [runtime expression] Date to compare from.
// Controller code.
aLittleAhead = DateAdd("d", 365, Now());

// View code.
<!--- Will output: about 1 year --->
#timeUntilInWords(aLittleAhead)#

titleize()

Global Helpers String Functions string controller model mapper migrator migration tabledefinition

Capitalizes all words in the text to create a nicer looking title.

Name Type Required Default Description
word string Yes The text to turn into a title.
<!--- Will output: CFWheels Is A Framework For ColdFusion --->
#titleize("CFWheels is a framework for ColdFusion")#

toggle()

Model Object CRUD Functions boolean model

Assigns to the property specified the opposite of the property's current boolean value. Throws an error if the property cannot be converted to a boolean value. Returns this object if save called internally is false.

Name Type Required Default Description
property string Yes
save boolean No true Argument to decide whether save the property after it has been toggled.
// Get an object, and toggle a boolean property
user = model("user").findByKey(58);
isSuccess = user.toggle("isActive"); // returns whether the object was saved properly

// You can also use a dynamic helper for this
isSuccess = user.toggleIsActive();

truncate()

Global Helpers String Functions string controller model migrator migration tabledefinition

Truncates text to the specified length and replaces the last characters with the specified truncate string (which defaults to "...").

Name Type Required Default Description
text string Yes The text to truncate.
length numeric No 30 Length to truncate the text to.
truncateString string No ... String to replace the last characters with.
<!--- Will output: CFWheels is a fra... --->
#truncate(text="CFWheels is a framework for ColdFusion", length=20)#

<!--- Will output: CFWheels is a framework (more) --->
#truncate(text="CFWheels is a framework for ColdFusion", truncateString=" (more)")#

uniqueidentifier()

Migrator Table Definition Functions any tabledefinition

adds UUID columns to table definition

Name Type Required Default Description
columnNames string No
default string No newid()
null boolean No

up()

Migrator Migration Functions void migration

Migrates up: will be executed when migrating your schema forward Along with down(), these are the two main functions in any migration file Only available in a migration CFC

function up() {
	transaction {
		try {
			// your code goes here
			t = createTable(name='myTable');
			t.timestamps();
			t.create();
		} catch (any e) {
			local.exception = e;
		}

		if (StructKeyExists(local, "exception")) {
			transaction action="rollback";
			throw(errorCode="1", detail=local.exception.detail, message=local.exception.message, type="any");
		} else {
			transaction action="commit";
		}
	}
}

update()

Model Object CRUD Functions boolean model

Updates the object with the supplied properties and saves it to the database. Returns true if the object was saved successfully to the database and false otherwise.

Name Type Required Default Description
properties struct No [runtime expression] The properties you want to set on the object (can also be passed in as named arguments).
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
reload boolean No false Set to true to force CFWheels to query the database even though an identical query for this model may have been run in the same request. (The default in CFWheels is to get the second query from the model's request-level cache.)
validate boolean No true Set to false to skip validations for this operation.
transaction string No [runtime expression] Set this to commit to update the database, rollback to run all the database queries but not commit them, or none to skip transaction handling altogether.
callbacks boolean No true Set to false to disable callbacks for this method.
allowExplicitTimestamps boolean No false Set this to true to allow explicit assignment of createdAt or updatedAt properties
// Get a post object and then update its title in the database
post = model("post").findByKey(33);
post.update(title="New version of Wheels just released");

// Get a post object and then update its title and other properties based on what is pased in from the URL/form
post = model("post").findByKey(params.key);
post.update(title="New version of Wheels just released", properties=params.post);

// If you have a `hasOne` association setup from `author` to `bio`, you can do a scoped call. (The `setBio` method below will call `bio.update(authorId=anAuthor.id)` internally.)
author = model("author").findByKey(params.authorId); 
bio = model("bio").findByKey(params.bioId); 
author.setBio(bio); 

// If you have a `hasMany` association setup from `owner` to `car`, you can do a scoped call. (The `addCar` method below will call `car.update(ownerId=anOwner.id)` internally.)
anOwner = model("owner").findByKey(params.ownerId); 
aCar = model("car").findByKey(params.carId); 
anOwner.addCar(aCar); 

// If you have a `hasMany` association setup from `post` to `comment`, you can do a scoped call. (The `removeComment` method below will call `comment.update(postId="")` internally.)
aPost = model("post").findByKey(params.postId); 
aComment = model("comment").findByKey(params.commentId); 
aPost.removeComment(aComment); // Get an object, and toggle a boolean property
user = model("user").findByKey(58); 
isSuccess = user.toggle("isActive"); // returns whether the object was saved properly

// You can also use a dynamic helper for this
isSuccess = user.toggleIsActive(); 

updateAll()

Model Class Update Functions numeric model

Updates all properties for the records that match the where argument. Property names and values can be passed in either using named arguments or as a struct to the properties argument. By default, objects will not be instantiated and therefore callbacks and validations are not invoked. You can change this behavior by passing in instantiate=true. This method returns the number of records that were updated.

Name Type Required Default Description
where string No Maps to the WHERE clause of the query (or HAVING when necessary). The following operators are supported: =, !=, <>, <, <=, >, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, and OR (note that the key words need to be written in upper case). You can also use parentheses to group statements. You do not need to specify the table name(s); CFWheels will do that for you.
include string No Associations that should be included in the query using INNER or LEFT OUTER joins (which join type that is used depends on how the association has been set up in your model). If all included associations are set on the current model, you can specify them in a list (e.g. department,addresses,emails). You can build more complex include strings by using parentheses when the association is set on an included model, like album(artist(genre)), for example. These complex include strings only work when returnAs is set to query though.
properties struct No [runtime expression] The properties you want to set on the object (can also be passed in as named arguments).
reload boolean No false Set to true to force CFWheels to query the database even though an identical query for this model may have been run in the same request. (The default in CFWheels is to get the second query from the model's request-level cache.)
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
instantiate boolean No false Whether or not to instantiate the object(s) first. When objects are not instantiated, any callbacks and validations set on them will be skipped.
validate boolean No true Set to false to skip validations for this operation.
transaction string No [runtime expression] Set this to commit to update the database, rollback to run all the database queries but not commit them, or none to skip transaction handling altogether.
callbacks boolean No true Set to false to disable callbacks for this method.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
// Update the `published` and `publishedAt` properties for all records that have `published=0`  
recordsUpdated = model("post").updateAll( published=1, publishedAt=Now(), where="published=0" );

// If you have a `hasMany` association setup from `post` to `comment`, you can do a scoped call. (The `removeAllComments` method below will call `model("comment").updateAll(postid="", where="postId=#post.id#")` internally.)  
post = model("post").findByKey(params.postId);
post.removeAllComments();

updateByKey()

Model Class Update Functions boolean model

Finds the object with the supplied key and saves it (if validation permits it) with the supplied properties and / or named arguments. Property names and values can be passed in either using named arguments or as a struct to the properties argument. Returns true if the object was found and updated successfully, false otherwise.

Name Type Required Default Description
key any Yes Primary key value(s) of the record to fetch. Separate with comma if passing in multiple primary key values. Accepts a string, list, or a numeric value.
properties struct No [runtime expression] The properties you want to set on the object (can also be passed in as named arguments).
reload boolean No false Set to true to force CFWheels to query the database even though an identical query for this model may have been run in the same request. (The default in CFWheels is to get the second query from the model's request-level cache.)
validate boolean No true Set to false to skip validations for this operation.
transaction string No [runtime expression] Set this to commit to update the database, rollback to run all the database queries but not commit them, or none to skip transaction handling altogether.
callbacks boolean No true Set to false to disable callbacks for this method.
includeSoftDeletes boolean No false Set to true to include soft-deleted records in the queries that this method runs.
// Updates the object with `33` as the primary key value with values passed in through the URL/form
result = model("post").updateByKey(33, params.post);

// Updates the object with `33` as the primary key using named arguments
result = model("post").updateByKey(key=33, title="New version of Wheels just released", published=1);

updateOne()

Model Class Update Functions boolean model

Gets an object based on the arguments used and updates it with the supplied properties. Returns true if an object was found and updated successfully, false otherwise.

Name Type Required Default Description
where string No Maps to the WHERE clause of the query (or HAVING when necessary). The following operators are supported: =, !=, <>, <, <=, >, >=, LIKE, NOT LIKE, IN, NOT IN, IS NULL, IS NOT NULL, AND, and OR (note that the key words need to be written in upper case). You can also use parentheses to group statements. You do not need to specify the table name(s); CFWheels will do that for you.
order string No Maps to the ORDER BY clause of the query. You do not need to specify the table name(s); CFWheels will do that for you.
properties struct No [runtime expression] The properties you want to set on the object (can also be passed in as named arguments).
reload boolean No false Set to true to force CFWheels to query the database even though an identical query for this model may have been run in the same request. (The default in CFWheels is to get the second query from the model's request-level cache.)
validate boolean No true Set to false to skip validations for this operation.
transaction string No [runtime expression] Set this to commit to update the database, rollback to run all the database queries but not commit them, or none to skip transaction handling altogether.
callbacks boolean No true Set to false to disable callbacks for this method.
includeSoftDeletes boolean No false
// Sets the `new` property to `1` on the most recently released product
result = model("product").updateOne(order="releaseDate DESC", new=1);

// If you have a `hasOne` association setup from `user` to `profile`, you can do a scoped call. (The `removeProfile` method below will call `model("profile").updateOne(where="userId=#aUser.id#", userId="")` internally.)
aUser = model("user").findByKey(params.userId);
aUser.removeProfile();

updateProperty()

Model Object CRUD Functions boolean model

Updates a single property and saves the record without going through the normal validation procedure. This is especially useful for boolean flags on existing records.

Name Type Required Default Description
property string No Name of the property to update the value for globally.
value any No Value to set on the given property globally.
parameterize any No true Set to true to use cfqueryparam on all columns, or pass in a list of property names to use cfqueryparam on those only.
transaction string No [runtime expression] Set this to commit to update the database, rollback to run all the database queries but not commit them, or none to skip transaction handling altogether.
callbacks boolean No true Set to false to disable callbacks for this method.
// Sets the `new` property to `1` through updateProperty()
product = model("product").findByKey(56);
product.updateProperty("new", 1);

updateRecord()

Migrator Migration Functions void migration

Updates an existing record in a table Only available in a migration CFC

Name Type Required Default Description
table string Yes The table name where the record is
where string No The where clause, i.e admin = 1

URLFor()

Global Helpers Miscellaneous Functions string controller model migrator migration tabledefinition

Creates an internal URL based on supplied arguments.

Name Type Required Default Description
route string No Name of a route that you have configured in config/routes.cfm.
controller string No Name of the controller to include in the URL.
action string No Name of the action to include in the URL.
key any No Key(s) to include in the URL.
params string No Any additional parameters to be set in the query string (example: wheels=cool&x=y). Please note that CFWheels uses the & and = characters to split the parameters and encode them properly for you. However, if you need to pass in & or = as part of the value, then you need to encode them (and only them), example: a=cats%26dogs%3Dtrouble!&b=1.
anchor string No Sets an anchor name to be appended to the path.
onlyPath boolean No true If true, returns only the relative URL (no protocol, host name or port).
host string No Set this to override the current host.
protocol string No Set this to override the current protocol.
port numeric No 0 Set this to override the current port number.
encode boolean No true Encode URL parameters using EncodeForURL(). Please note that this does not make the string safe for placement in HTML attributes, for that you need to wrap the result in EncodeForHtmlAttribute() or use linkTo(), startFormTag() etc instead.
<!--- Create the URL for the `logOut` action on the `account` controller, typically resulting in `/account/log-out` --->
#urlFor(controller="account", action="logOut")#

<!--- Create a URL with an anchor set on it --->
#urlFor(action="comments", anchor="comment10")#

<!--- Create a URL based on a route called `products`, which expects params for `categorySlug` and `productSlug` --->
#urlFor(route="product", categorySlug="accessories", productSlug="battery-charger")#

usesLayout()

Controller Configuration Functions void controller

Used within a controller's config() function to specify controller- or action-specific layouts.

Name Type Required Default Description
template string Yes Name of the layout template or function name you want to use.
ajax string No Name of the layout template you want to use for AJAX requests.
except string No List of actions that should not get the layout.
only string No List of actions that should only get the layout.
useDefault boolean No true When specifying conditions or a function, pass in true to use the default layout.cfm if none of the conditions are met.
// We want this layout to be used as the default throughout the 
// entire controller, except for the `myAjax` action. 
usesLayout(template="myLayout", except="myAjax"); 

// Use a custom layout for these actions but use the default 
// `layout.cfm` for the rest. 
usesLayout(template="myLayout", only="termsOfService,shippingPolicy"); 

// Define a custom function to decide which layout to display.
// The `setLayout` function should return the name of the layout 
// to use or `true` to use the default one. 
usesLayout("setLayout");

valid()

Model Object Error Functions boolean model

Runs the validation on the object and returns true if it passes it. CFWheels will run the validation process automatically whenever an object is saved to the database, but sometimes it's useful to be able to run this method to see if the object is valid without saving it to the database.

Name Type Required Default Description
callbacks boolean No true Set to false to disable callbacks for this method.
// Check if a user is valid before proceeding with execution
user = model("user").new(params.user);

if user.valid(){
    // Do something here
}

validate()

Model Configuration Validation Functions void model

Registers method(s) that should be called to validate objects before they are saved.

Name Type Required Default Description
methods string No Method name or list of method names to call. Can also be called with the method argument.
condition string No String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unless string No String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).
when string No onSave Pass in onCreate or onUpdate to limit when this validation occurs (by default validation will occur on both create and update, i.e. onSave).
function config() {
	// Register the `checkPhoneNumber` method below to be called to validate objects before they are saved.
	validate("checkPhoneNumber");
}

function checkPhoneNumber() {
	// Make sure area code is `614`.
	return Left(this.phoneNumber, 3) == "614";
}

validateOnCreate()

Model Configuration Validation Functions void model

Registers method(s) that should be called to validate new objects before they are inserted.

Name Type Required Default Description
methods string No Method name or list of method names to call. Can also be called with the method argument.
condition string No String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unless string No String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).
function config(){
	// Register the `checkPhoneNumber` method below to be called to validate new objects before they are inserted.
	validateOnCreate("checkPhoneNumber");
}

function checkPhoneNumber(){
	// Make sure area code is `614`.
	return Left(this.phoneNumber, 3) == "614";
}

validateOnUpdate()

Model Configuration Validation Functions void model

Registers method(s) that should be called to validate existing objects before they are updated.

Name Type Required Default Description
methods string No Method name or list of method names to call. Can also be called with the method argument.
condition string No String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unless string No String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).
function config(){
	// Register the `check` method below to be called to validate existing objects before they are updated.
	validateOnUpdate("checkPhoneNumber");
}

function checkPhoneNumber(){
	// Make sure area code is `614`
	return Left(this.phoneNumber, 3) == "614";
}

validatesConfirmationOf()

Model Configuration Validation Functions void model

Validates that the value of the specified property also has an identical confirmation value. This is common when having a user type in their email address a second time to confirm, confirming a password by typing it a second time, etc. The confirmation value only exists temporarily and never gets saved to the database. By convention, the confirmation property has to be named the same as the property with "Confirmation" appended at the end. Using the password example, to confirm our password property, we would create a property called passwordConfirmation.

Name Type Required Default Description
properties string No Name of property or list of property names to validate against (can also be called with the property argument).
message string No [property] should match confirmation Supply a custom error message here to override the built-in one.
when string No onSave Pass in onCreate or onUpdate to limit when this validation occurs (by default validation will occur on both create and update, i.e. onSave).
condition string No String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unless string No String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).
caseSensitive boolean No false Ensure the confirmed property comparison is case sensitive
// Make sure that the user has to confirm their password correctly the first time they register (usually done by typing it again in a second form field)
validatesConfirmationOf(property="password", when="onCreate", message="Your password and its confirmation do not match. Please try again.");

validatesExclusionOf()

Model Configuration Validation Functions void model

Validates that the value of the specified property does not exist in the supplied list.

Name Type Required Default Description
properties string No Name of property or list of property names to validate against (can also be called with the property argument).
list string Yes Single value or list of values that should not be allowed.
message string No [property] is reserved Supply a custom error message here to override the built-in one.
when string No onSave Pass in onCreate or onUpdate to limit when this validation occurs (by default validation will occur on both create and update, i.e. onSave).
allowBlank boolean No false If set to true, validation will be skipped if the property value is an empty string or doesn't exist at all. This is useful if you only want to run this validation after it passes the validatesPresenceOf test, thus avoiding duplicate error messages if it doesn't.
condition string No String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unless string No String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).
// Do not allow "PHP" or "Fortran" to be saved to the database as a cool language
validatesExclusionOf(property="coolLanguage", list="php,fortran", message="Haha, you can not be serious. Try again, please.");

validatesFormatOf()

Model Configuration Validation Functions void model

Validates that the value of the specified property is formatted correctly by matching it against a regular expression using the regEx argument and / or against a built-in CFML validation type using the type argument (creditcard, date, email, etc.).

Name Type Required Default Description
properties string No Name of property or list of property names to validate against (can also be called with the property argument).
regEx string No Regular expression to verify against.
type string No One of the following types to verify against: creditcard, date, email, eurodate, guid, social_security_number, ssn, telephone, time, URL, USdate, UUID, variableName, zipcode (will be passed through to your CFML engine's IsValid() function).
message string No [property] is invalid Supply a custom error message here to override the built-in one.
when string No onSave Pass in onCreate or onUpdate to limit when this validation occurs (by default validation will occur on both create and update, i.e. onSave).
allowBlank boolean No false If set to true, validation will be skipped if the property value is an empty string or doesn't exist at all. This is useful if you only want to run this validation after it passes the validatesPresenceOf test, thus avoiding duplicate error messages if it doesn't.
condition string No String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unless string No String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).
// Make sure that the user has entered a correct credit card validatesFormatOf(property="cc", type="creditcard"); /*  * Make sure that the user has entered an email address ending with the  * `.se` domain when the `ipCheck()` method returns `true`, and it's not  * Sunday. Also supply a custom error message that overrides the CFWheels  * default one  */ validatesFormatOf( property="email", regEx="^.*@.*\.se$", condition="ipCheck()", unless="DayOfWeek() eq 1" message="Sorry, you must have a Swedish email address to use this website." );

validatesInclusionOf()

Model Configuration Validation Functions void model

Validates that the value of the specified property exists in the supplied list.

Name Type Required Default Description
properties string No Name of property or list of property names to validate against (can also be called with the property argument).
list string Yes List of allowed values.
message string No [property] is not included in the list Supply a custom error message here to override the built-in one.
when string No onSave Pass in onCreate or onUpdate to limit when this validation occurs (by default validation will occur on both create and update, i.e. onSave).
allowBlank boolean No false If set to true, validation will be skipped if the property value is an empty string or doesn't exist at all. This is useful if you only want to run this validation after it passes the validatesPresenceOf test, thus avoiding duplicate error messages if it doesn't.
condition string No String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unless string No String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).
// Make sure that the user selects either "CFWheels" or "Rails" as their framework 
validatesInclusionOf(property="frameworkOfChoice", list="cfwheels,rails", message="Please try again, and this time, select a decent framework!" );

validatesLengthOf()

Model Configuration Validation Functions void model

Validates that the value of the specified property matches the length requirements supplied. Use the exactly, maximum, minimum and within arguments to specify the length requirements.

Name Type Required Default Description
properties string No Name of property or list of property names to validate against (can also be called with the property argument).
message string No [property] is the wrong length Supply a custom error message here to override the built-in one.
when string No onSave Pass in onCreate or onUpdate to limit when this validation occurs (by default validation will occur on both create and update, i.e. onSave).
allowBlank boolean No false If set to true, validation will be skipped if the property value is an empty string or doesn't exist at all. This is useful if you only want to run this validation after it passes the validatesPresenceOf test, thus avoiding duplicate error messages if it doesn't.
exactly numeric No 0 The exact length that the property value must be.
maximum numeric No 0 The maximum length that the property value can be.
minimum numeric No 0 The minimum length that the property value can be.
within string No A list of two values (minimum and maximum) that the length of the property value must fall within.
condition string No String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unless string No String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).
// Make sure that the `firstname` and `lastName` properties are not more than
// 50 characters and use square brackets to dynamically insert the property
// name when the error message is displayed to the user. (The `firstName`
// property will be displayed as "first name".)
validatesLengthOf(
    properties="firstName,lastName",
    maximum=50,
    message="Please shorten your [property] please (50 characters max)."
);

// Make sure that the `password` property is between 4 and 15 characters
validatesLengthOf(
    property="password",
    within="4,20",
    message="The password length must be between 4 and 20 characters."
);

validatesNumericalityOf()

Model Configuration Validation Functions void model

Validates that the value of the specified property is numeric.

Name Type Required Default Description
properties string No Name of property or list of property names to validate against (can also be called with the property argument).
message string No [property] is not a number Supply a custom error message here to override the built-in one.
when string No onSave Pass in onCreate or onUpdate to limit when this validation occurs (by default validation will occur on both create and update, i.e. onSave).
allowBlank boolean No false If set to true, validation will be skipped if the property value is an empty string or doesn't exist at all. This is useful if you only want to run this validation after it passes the validatesPresenceOf test, thus avoiding duplicate error messages if it doesn't.
onlyInteger boolean No false Specifies whether the property value must be an integer.
condition string No String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unless string No String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).
odd boolean No
even boolean No
greaterThan numeric No Specifies whether or not the value must be greater than the supplied value.
greaterThanOrEqualTo numeric No Specifies whether or not the value must be greater than or equal the supplied value.
equalTo numeric No Specifies whether or not the value must be equal to the supplied value.
lessThan numeric No Specifies whether or not the value must be less than the supplied value.
lessThanOrEqualTo numeric No Specifies whether or not the value must be less than or equal the supplied value.
// Make sure that the score is a number with no decimals but only when a score is supplied. (Tetting `allowBlank` to `true` means that objects are allowed to be saved without scores, typically resulting in `NULL` values being inserted in the database table)
validatesNumericalityOf(property="score", onlyInteger=true, allowBlank=true, message="Please enter a correct score.");

validatesPresenceOf()

Model Configuration Validation Functions void model

Validates that the specified property exists and that its value is not blank.

Name Type Required Default Description
properties string No Name of property or list of property names to validate against (can also be called with the property argument).
message string No [property] can't be empty Supply a custom error message here to override the built-in one.
when string No onSave Pass in onCreate or onUpdate to limit when this validation occurs (by default validation will occur on both create and update, i.e. onSave).
condition string No String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unless string No String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).
// Make sure that the user data can not be saved to the database without the `emailAddress` property. (It must exist and not be an empty string)
validatesPresenceOf("emailAddress");

validatesUniquenessOf()

Model Configuration Validation Functions void model

Validates that the value of the specified property is unique in the database table. Useful for ensuring that two users can't sign up to a website with identical usernames for example. When a new record is created, a check is made to make sure that no record already exists in the database table with the given value for the specified property. When the record is updated, the same check is made but disregarding the record itself.

Name Type Required Default Description
properties string No Name of property or list of property names to validate against (can also be called with the property argument).
message string No [property] has already been taken Supply a custom error message here to override the built-in one.
when string No onSave Pass in onCreate or onUpdate to limit when this validation occurs (by default validation will occur on both create and update, i.e. onSave).
allowBlank boolean No false If set to true, validation will be skipped if the property value is an empty string or doesn't exist at all. This is useful if you only want to run this validation after it passes the validatesPresenceOf test, thus avoiding duplicate error messages if it doesn't.
scope string No One or more properties by which to limit the scope of the uniqueness constraint.
condition string No String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).
unless string No String expression to be evaluated that decides if validation will be run (if the expression returns false validation will run).
includeSoftDeletes boolean No true Set to true to include soft-deleted records in the queries that this method runs.
// Make sure that two users with the same username won't ever exist in the database table
validatesUniquenessOf(property="username", message="Sorry, that username is already taken.");

// Same as above but allow identical usernames as long as they belong to a different account
validatesUniquenessOf(property="username", scope="accountId");

validationTypeForProperty()

Model Class Miscellaneous Functions any model

Returns the validation type for the property.

Name Type Required Default Description
property string Yes Name of column to retrieve data for.
// first name is a varchar(50) column
employee = model("employee").new();

<!--- would output "string"--->
#employee.validationTypeForProperty("firstName")#

verificationChain()

Controller Configuration Functions array controller

Returns an array of all the verifications set on this controller in the order in which they will be executed.

// Get verification chain, remove the first item, and set it back.
myVerificationChain = verificationChain();
ArrayDeleteAt(myVerificationChain, 1);
setVerificationChain(myVerificationChain);

verifies()

Controller Configuration Functions void controller

Instructs CFWheels to verify that some specific criterias are met before running an action. Note that all undeclared arguments will be passed to redirectTo() call if a handler is not specified.

Name Type Required Default Description
only string No List of action names to limit this verification to.
except string No List of action names to exclude this verification from.
post any No Set to true to verify that this is a POST request.
get any No Set to true to verify that this is a GET request.
ajax any No Set to true to verify that this is an AJAX request.
cookie string No Verify that the passed in variable name exists in the cookie scope.
session string No Verify that the passed in variable name exists in the session scope.
params string No Verify that the passed in variable name exists in the params struct.
handler string No Pass in the name of a function that should handle failed verifications. The default is to just abort the request when a verification fails.
cookieTypes string No List of types to check each listed cookie value against (will be passed through to your CFML engine's IsValid function).
sessionTypes string No List of types to check each list session value against (will be passed through to your CFML engine's IsValid function).
paramsTypes string No List of types to check each params value against (will be passed through to your CFML engine's IsValid function).
// Tell CFWheels to verify that the `handleForm` action is always a `POST` request when executed.
verifies(only="handleForm", post=true);

// Make sure that the edit action is a `GET` request, that `userId` exists in the `params` struct, and that it's an integer.
verifies(only="edit", get=true, params="userId", paramsTypes="integer");

// Just like above, only this time we want to invoke a custom function in our controller to handle the request when it is invalid.
verifies(only="edit", get=true, params="userId", paramsTypes="integer", handler="myCustomFunction");

// Just like above, only this time instead of specifying a handler, we want to `redirect` the visitor to the index action of the controller and show an error in The Flash when the request is invalid.
verifies(only="edit", get=true, params="userId", paramsTypes="integer", action="index", error="Invalid userId");

wildcard()

Configuration Routing struct mapper

Special wildcard matching generates routes with `

Name Type Required Default Description
method string No get List of HTTP methods (verbs) to generate the wildcard routes for. We strongly recommend leaving the default value of get and using other routing mappers if you need to POST to a URL endpoint. For better readability, you can also pass this argument as methods if you're listing multiple methods.
action string No index Default action to specify if the value for the [action] placeholder is not provided.
mapKey boolean No false Whether or not to enable a [key] matcher, enabling a [controller]/[action]/[key] pattern.
mapFormat boolean No false Whether or not to add an optional .[format] pattern to the end of the generated routes. This is useful for providing formats via URL like json, xml, pdf, etc.
<cfscript>

mapper()
    // Enables `[controller]` and `[controller]/[action]`, only via `GET` requests.
    .wildcard()

    // Enables `[controller]/[action]/[key]` as well.
    .wildcard(mapKey=true)

    // Also enables patterns like `[controller].[format]` and
    // `[controller]/[action].[format]`
    .wildcard(mapFormat=true)

    // Allow additional methods beyond just `GET`
    //
    // Note that this can open some serious security holes unless you use `verifies`
    // in the controller to make sure that requests changing data can only occur
    // with a `POST` method.
    .wildcard(methods="get,post")
.end();

</cfscript>

wordTruncate()

Global Helpers String Functions string controller model migrator migration tabledefinition

Truncates text to the specified length of words and replaces the remaining characters with the specified truncate string (which defaults to "...").

Name Type Required Default Description
text string Yes The text to truncate.
length numeric No 5 Number of words to truncate the text to.
truncateString string No ... String to replace the last characters with.
<!--- Outputs "CFWheels is a framework..." --->
#wordTruncate(text="CFWheels is a framework for ColdFusion", length=4)#

yearSelectTag()

View Helpers Form Tag Functions string controller

Builds and returns a string containing a select form control for a range of years based on the supplied name.

Name Type Required Default Description
name string Yes Name to populate in tag's name attribute.
selected string No The year that should be selected initially.
startYear numeric No 2019 First year in select list.
endYear numeric No 2029 Last year in select list.
includeBlank any No false Whether to include a blank option in the select form control. Pass true to include a blank line or a string that should represent what display text should appear for the empty value (for example, "- Select One -").
label string No The label text to use in the form control.
labelPlacement string No around Whether to place the label before, after, or wrapped around the form control. Label text placement can be controlled using aroundLeft or aroundRight.
prepend string No String to prepend to the form control. Useful to wrap the form control with HTML tags.
append string No String to append to the form control. Useful to wrap the form control with HTML tags.
prependToLabel string No String to prepend to the form control's label. Useful to wrap the form control with HTML tags.
appendToLabel string No String to append to the form control's label. Useful to wrap the form control with HTML tags.
encode any No true Use this argument to decide whether the output of the function should be encoded in order to prevent Cross Site Scripting (XSS) attacks. Set it to true to encode all relevant output for the specific HTML element in question (e.g. tag content, attribute values, and URLs). For HTML elements that have both tag content and attribute values you can set this argument to attributes to only encode attribute values and not tag content.
<!--- View Code --->
#yearSelectTag(name="yearOfBirthday", selected=params.yearOfBirthday)#

// Only allow selection of year to be for the past 50 years, minimum being 18 years ago
fiftyYearsAgo = Now() - 50;
eighteenYearsAgo = Now() - 18;

<!--- View Code --->
#yearSelectTag(name="yearOfBirthday", selected=params.yearOfBirthday, startYear=fiftyYearsAgo, endYear=eighteenYearsAgo)#