Finally, a framework for the rest of us!

CFWheels is an open source CFML (ColdFusion Markup Language) framework inspired by Ruby on Rails that provides fast application development, a great organization system for your code, and is just plain fun to use.

One of our biggest goals is for you to be able to get up and running with CFWheels quickly. We want for you to be able to learn it as rapidly as it is to write applications with it.

Get Started    
Suggest Edits

afterCreate()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset afterCreate("fixObj")>
Suggest Edits

afterDelete()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset afterDelete("fixObj")>
Suggest Edits

afterFind()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `setTime` method after getting objects or records with one of the finder methods --->
<cffunction name="init">
	<cfset afterFind("setTime")>
</cffunction>

<cffunction name="setTime">
	<cfset arguments.fetchedAt = Now()>
	<cfreturn arguments>
</cffunction>
Suggest Edits

afterInitialization()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset afterInitialization("fixObj")>
Suggest Edits

afterNew()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

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 --->
<cfset afterNew("fixObj")>
Suggest Edits

afterSave()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset afterSave("fixObj")>
Suggest Edits

afterUpdate()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset afterUpdate("fixObj")>
Suggest Edits

afterValidation()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset afterValidation("fixObj")>
Suggest Edits

afterValidationOnCreate()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset afterValidationOnCreate("fixObj")>
Suggest Edits

afterValidationOnUpdate()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset afterValidationOnUpdate("fixObj")>
Suggest Edits

automaticValidations()

Whether or not to enable default validations for this model.

 
Parameter
Type
Required
Default
Description

value

boolean

true

Set to true or false.

// In `models/User.cfc`, disable automatic validations. In this case, automatic validations are probably enabled globally, but we want to disable just for this model.
<cffunction name="init">
	<cfscript>
		automaticValidations(false);
	</cfscript>
</cffunction>
Suggest Edits

beforeCreate()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset beforeCreate("fixObj")>
Suggest Edits

beforeDelete()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset beforeDelete("fixObj")>
Suggest Edits

beforeSave()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset beforeSave("fixObj")>
Suggest Edits

beforeUpdate()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset beforeUpdate("fixObj")>
Suggest Edits

beforeValidation()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset beforeValidation("fixObj")>
Suggest Edits

beforeValidationOnCreate()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset beforeValidationOnCreate("fixObj")>
Suggest Edits

beforeValidationOnUpdate()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for afterNew.

<!--- Instruct CFWheels to call the `fixObj` method --->
<cfset beforeValidationOnUpdate("fixObj")>
Suggest Edits

accessibleProperties()

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

 
accessibleProperties([ properties ])
Parameter
Type
Required
Default
Description

properties

string

No

Property name (or list of property names) that are allowed to be altered through mass assignment.

<!--- In `models/User.cfc`, only `isActive` can be set through mass assignment operations like `updateAll()` --->
<cffunction name="init">
    <cfset accessibleProperties("isActive")>
</cffunction>
Suggest Edits

dataSource()

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

 
dataSource(datasource [, username, password ])
Parameter
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 --->
<cffunction name="init">
    <!--- Tell Wheels to use the data source named `users_source` instead of the default one whenever this model makes SQL calls  --->
              <cfset dataSource("users_source")>
</cffunction>
Suggest Edits

isClass()

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

 
isClass()
<!--- Use the passed in `id` when we're already in an instance --->
<cffunction name="memberIsAdmin">
    <cfif isClass()>
        <cfreturn this.findByKey(arguments.id).admin>
    <cfelse>
        <cfreturn this.admin>
    </cfif>
</cffunction>
Suggest Edits

isInstance()

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

 
isInstance()
<!--- Use the passed in `id` when we're not already in an instance --->
<cffunction name="memberIsAdmin">
    <cfif isInstance()>
        <cfreturn this.admin>
    <cfelse>
        <cfreturn this.findByKey(arguments.id).admin>
    </cfif>
</cffunction>
Suggest Edits

property()

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 Wheels performs.

 
property(name [, column, sql, label, defaultValue ])
Parameter
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

A 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.

<!--- 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) --->
<cfset 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 --->
<cfset 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 --->
<cfset 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` --->
<cfset property(name="firstName", defaultValue="Dave")>
Suggest Edits

protectedProperties()

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

 
protectedProperties([ properties ])
Parameter
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()` --->
<cffunction name="init">
    <cfset protectedProperties("firstName,lastName")>
</cffunction>
Suggest Edits

setPrimaryKey()

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. Also aliased as setPrimaryKeys().

 
setPrimaryKey(property)
Parameter
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` --->
<cffunction name="init">
    <cfset setPrimaryKey("userID")>
</cffunction>
Suggest Edits

setPrimaryKeys()

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

 
setPrimaryKeys(property)
Parameter
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` --->
<cffunction name="init">
    <cfset setPrimaryKeys("customerId,publicationId")>
</cffunction>
Suggest Edits

setTableNamePrefix()

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

 
setTableNamePrefix(prefix)
Parameter
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` --->
<cffunction name="init">
    <cfset setTableNamePrefix("tbl")>
</cffunction>
Suggest Edits

table()

Use this method to tell Wheels 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 Wheels 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).

 
table(name)
Parameter
Type
Required
Default
Description

name

any

Yes

Name of the table to map this model to.

<!--- In models/User.cfc --->
<cffunction name="init">
    <!--- Tell Wheels to use the `tbl_USERS` table in the database for the `user` model instead of the default (which would be `users`) --->
    <cfset table("tbl_USERS")>
</cffunction>
Suggest Edits

belongsTo()

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.

 
Parameter
Type
Required
Default
Description

name

string

true

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

false

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

false

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

false

Column name to join to if not the primary key (usually not needed if you follow wheels conventions since the join key will be the tables primary key/keys).

joinType

string

false

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");
Suggest Edits

hasMany()

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

 
Parameter
Type
Required
Default
Description

name

string

true

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

false

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

false

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

false

Column name to join to if not the primary key (usually not needed if you follow wheels conventions since the join key will be the tables primary key/keys).

joinType

string

false

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

false

false

Defines how to handle dependent models when you delete a record from this model. Set to delete to instantiate associated models and call their delete method, deleteAll to delete without instantiating, removeAll to remove the foreign key, or false to do nothing.

shortcut

string

false

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

false

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 `init()` method
hasMany(name="subscriptions", shortcut="magazines", through="publication,subscriptions");

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

// In the models/Publication `init()` method
hasMany("subscriptions");
Suggest Edits

hasOne()

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

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for belongsTo.

modelName

string

false

See documentation for belongsTo.

foreignKey

string

false

See documentation for belongsTo.

joinKey

string

false

See documentation for belongsTo.

joinType

string

false

outer

See documentation for belongsTo.

dependent

string

false

false

See documentation for hasMany.

// 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");
Suggest Edits

nestedProperties()

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

 
Parameter
Type
Required
Default
Description

association

string

false

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

false

true

Whether to save the association(s) when the parent object is saved.

allowDelete

boolean

false

false

Set allowDelete 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

false

Set sortProperty 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

false

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 --->
<cffunction name="init">
	<cfset hasMany("groupEntitlements")>
	<cfset nestedProperties(association="groupEntitlements", allowDelete=true)>
</cffunction>
Suggest Edits

validate()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

Method name or list of method names to call. (Can also be called with the method argument.)

condition

string

false

See documentation for validatesConfirmationOf.

unless

string

false

See documentation for validatesConfirmationOf.

when

string

false

onSave

See documentation for validatesConfirmationOf.

<cffunction name="init">
	<cfscript>
		// Register the `checkPhoneNumber` method below to be called to validate objects before they are saved
		validate("checkPhoneNumber");
	</cfscript>
</cffunction>

<cffunction name="checkPhoneNumber">
	<cfscript>
		// Make sure area code is `614`
		return Left(this.phoneNumber, 3) == "614";
	</cfscript>
</cffunction>
Suggest Edits

validateOnCreate()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for validate.

condition

string

false

See documentation for validatesConfirmationOf.

unless

string

false

See documentation for validatesConfirmationOf.

<cffunction name="init">
	<cfscript>
		// Register the `checkPhoneNumber` method below to be called to validate new objects before they are inserted
		validateOnCreate("checkPhoneNumber");
	</cfscript>
</cffunction>

<cffunction name="checkPhoneNumber">
	<cfscript>
		// Make sure area code is `614`
		return Left(this.phoneNumber, 3) == "614";
	</cfscript>
</cffunction>
Suggest Edits

validateOnUpdate()

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

 
Parameter
Type
Required
Default
Description

methods

string

false

See documentation for validate.

condition

string

false

See documentation for validatesConfirmationOf.

unless

string

false

See documentation for validatesConfirmationOf.

<cffunction name="init">
	<cfscript>
		// Register the `check` method below to be called to validate existing objects before they are updated
		validateOnUpdate("checkPhoneNumber");
	</cfscript>
</cffunction>

<cffunction name="checkPhoneNumber">
	<cfscript>
		// Make sure area code is `614`
		return Left(this.phoneNumber, 3) == "614";
	</cfscript>
</cffunction>
Suggest Edits

validatesConfirmationOf()

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.

 
Parameter
Type
Required
Default
Description

properties

string

true

Name of property or list of property names to validate against (can also be called with the property argument).

message

string

false

[property] should match confirmation

Supply a custom error message here to override the built-in one.

when

string

false

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

false

String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).

unless

string

false

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 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.");
Suggest Edits

validatesExclusionOf()

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

 
Parameter
Type
Required
Default
Description

properties

string

true

See documentation for validatesConfirmationOf.

list

string

true

Single value or list of values that should not be allowed.

message

string

false

[property] is reserved

See documentation for validatesConfirmationOf.

when

string

false

onSave

See documentation for validatesConfirmationOf.

allowBlank

boolean

false

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

false

See documentation for validatesConfirmationOf.

unless

string

false

See documentation for validatesConfirmationOf.

// 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.");
Suggest Edits

validatesFormatOf()

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.).

 
Parameter
Type
Required
Default
Description

properties

string

true

Name of property or list of property names to validate against (can also be called with the property argument).

regEx

string

false

Regular expression to verify against.

type

string

false

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

false

[property] is invalid

Supply a custom error message here to override the built-in one.

when

string

false

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

false

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

false

String expression to be evaluated that decides if validation will be run. (If the expression returns true, validation will run.)

unless

string

false

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."
);
Suggest Edits

validatesInclusionOf()

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

 
Parameter
Type
Required
Default
Description

properties

string

true

Name of property or list of property names to validate against (can also be called with the property argument).

list

string

true

List of allowed values.

message

string

false

[property] is not included in the list

Supply a custom error message here to override the built-in one.

when

string

false

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

false

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

false

String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).

unless

string

false

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!"
);
Suggest Edits

validatesLengthOf()

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.

 
Parameter
Type
Required
Default
Description

properties

string

true

Name of property or list of property names to validate against (can also be called with the property argument).

message

string

false

[property] is the wrong length

Supply a custom error message here to override the built-in one.

when

string

false

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

false

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

false

0

The exact length that the property value must be.

maximum

numeric

false

0

The maximum length that the property value can be.

minimum

numeric

false

0

The minimum length that the property value can be.

within

string

false

A list of two values (minimum and maximum) that the length of the property value must fall within.

condition

string

false

String expression to be evaluated that decides if validation will be run (if the expression returns true validation will run).

unless

string

false

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."
);
Suggest Edits

validatesNumericalityOf()

Validates that the value of the specified property is numeric.

 
Parameter
Type
Required
Default
Description

properties

string

true

See documentation for validatesConfirmationOf.

message

string

false

[property] is not a number

See documentation for validatesConfirmationOf.

when

string

false

onSave

See documentation for validatesConfirmationOf.

allowBlank

boolean

false

false

See documentation for validatesExclusionOf.

onlyInteger

boolean

false

false

Specifies whether the property value must be an integer.

condition

string

false

See documentation for validatesConfirmationOf.

unless

string

false

See documentation for validatesConfirmationOf.

odd

boolean

false

Specifies whether or not the value must be an odd number.

even

boolean

false

Specifies whether or not the value must be an even number.

greaterThan

numeric

false

Specifies whether or not the value must be greater than the supplied value.

greaterThanOrEqualTo

numeric

false

Specifies whether or not the value must be greater than or equal the supplied value.

equalTo

numeric

false

Specifies whether or not the value must be equal to the supplied value.

lessThan

numeric

false

Specifies whether or not the value must be less than the supplied value.

lessThanOrEqualTo

numeric

false

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.");
Suggest Edits

validatesPresenceOf()

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

 
Parameter
Type
Required
Default
Description

properties

string

true

See documentation for validatesConfirmationOf.

message

string

false

[property] can't be empty

See documentation for validatesConfirmationOf.

when

string

false

onSave

See documentation for validatesConfirmationOf.

condition

string

false

See documentation for validatesConfirmationOf.

unless

string

false

See documentation for validatesConfirmationOf.

// 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");
Suggest Edits

validatesUniquenessOf()

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.

 
Parameter
Type
Required
Default
Description

properties

string

true

Name of property or list of property names to validate against (can also be called with the property argument).

message

string

false

[property] has already been taken

Supply a custom error message here to override the built-in one.

when

string

false

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

false

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

false

One or more properties by which to limit the scope of the uniqueness constraint.

condition

string

false

String expression to be evaluated that decides if validation will be run (if the expression returns true, validation will run).

unless

string

false

String expression to be evaluated that decides if validation will be run (if the expression returns false, validation will run).

includeSoftDeletes

boolean

false

true

Whether to take records deleted using "Soft Delete" into account when performing the uniqueness check.

// 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");

Still seeing duplicates?

We recommend passing in isolation="serializable" when saving your object to the database to avoid possible race conditions.

You can also add a uniqueness constraint to the column in the database. This would protect you against changes coming from other sources than the CFWheels app.

Suggest Edits

Model Class Functions

These methods operate on the class as a whole and not on individual objects and thus need to be prefaced with model("name"). You can call these methods from anywhere, but it is not recommended to call them from view pages. When calling them from their own model files, it is recommended to reference the scope explicitly with the this keyword.

 
Suggest Edits

average()

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.

 
Parameter
Type
Required
Default
Description

property

string

true

Name of the property to calculate the average for.

where

string

false

See documentation for findAll.

include

string

false

See documentation for findAll.

distinct

boolean

false

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

false

true

See documentation for findAll.

ifNull

any

false

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

false

false

See documentation for findAll.

group

string

false

See documentation for findAll.

// 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);
Suggest Edits

count()

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.

 
Parameter
Type
Required
Default
Description

where

string

false

This argument maps to the WHERE clause of the query. 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. Instead of using the where argument, you can create cleaner code by making use of a concept called Dynamic Finders.

include

string

false

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

false

false

Set to true to force CFWheels to query the database even though an identical query may have been run in the same request. (The default in CFWheels is to get the second query from the request-level cache.)

parameterize

any

false

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

false

false

You can set this argument to true to include soft-deleted records in the results.

group

string

false

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();
Suggest Edits

create()

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.

 
Parameter
Type
Required
Default
Description

properties

struct

false

See documentation for new.

parameterize

any

false

true

See documentation for findAll.

reload

boolean

false

false

See documentation for save.

validate

boolean

false

true

See documentation for save.

transaction

string

false

See documentation for save.

callbacks

boolean

false

true

See documentation for save.

<!--- Create a new author and save it to the database --->
<cfset newAuthor = model("author").create(params.author)>

<!--- Same as above using named arguments --->
<cfset newAuthor = model("author").create(firstName="John", lastName="Doe")>

<!--- Same as above using both named arguments and a struct --->
<cfset 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.) --->
<cfset aCustomer = model("customer").findByKey(params.customerId)>
<cfset anOrder = aCustomer.createOrder(shipping=params.shipping)>
Suggest Edits

deleteAll()

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.

 
deleteAll([ where, include, reload, parameterize, instantiate, transaction, callbacks, includeSoftDeletes, softDelete ])
Parameter
Type
Required
Default
Description

where

string

No

This argument maps to the WHERE clause of the query. 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); Wheels 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 Wheels to query the database even though an identical query may have been run in the same request. (The default in Wheels is to get the second query from the 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 when the save has completed, 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 operation.

includeSoftDeletes

boolean

No

false

You can set this argument to true to include soft-deleted records in the results.

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) --->
<cfset 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.) --->
<cfset post = model("post").findByKey(params.postId)>
<cfset howManyDeleted = post.deleteAllComments()>
Suggest Edits

deleteByKey()

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

 
deleteByKey(key [, reload, transaction, callbacks, includeSoftDeletes, softDelete ])
Parameter
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 Wheels to query the database even though an identical query may have been run in the same request. (The default in Wheels is to get the second query from the request-level cache.)

transaction

string

No

[runtime expression]

Set this to commit to update the database when the save has completed, 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 operation.

includeSoftDeletes

boolean

No

false

You can set this argument to true to include soft-deleted records in the results.

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` --->
<cfset result = model("user").deleteByKey(1)>
Suggest Edits

deleteOne()

Gets an object based on conditions and deletes it.

 
deleteOne([ where, order, reload, transaction, callbacks, includeSoftDeletes, softDelete ])
Parameter
Type
Required
Default
Description

where

string

No

This argument maps to the WHERE clause of the query. 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); Wheels 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); Wheels will do that for you.

reload

boolean

No

false

Set to true to force Wheels to query the database even though an identical query may have been run in the same request. (The default in Wheels is to get the second query from the request-level cache.)

transaction

string

No

[runtime expression]

Set this to commit to update the database when the save has completed, 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 operation.

includeSoftDeletes

boolean

No

false

You can set this argument to true to include soft-deleted records in the results.

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 --->
<cfset 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) --->
<cfset aUser = model("user").findByKey(params.userId)>
<cfset aUser.deleteProfile()>
Suggest Edits

columnDataForProperty()

Returns a struct with data for the named property.

 
columnDataForProperty(property)
Parameter
Type
Required
Default
Description

property

string

Yes

Name of column to retrieve data for.

<!--- Get an object, set a value and then see if the property exists --->
<cfset employee = model("employee").new()>
<cfset employee.columnDataForProperty("firstName")><!--- returns column struct --->
Suggest Edits

columnForProperty()

Returns the column name mapped for the named model property.

 
columnForProperty(property)
Parameter
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 --->
<cfset employee = model("employee").new()>
<cfset employee.columnForProperty("firstName")><!--- returns column name, in this case "firstname" if the convention is used --->
Suggest Edits

columnNames()

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.

 
columnNames()
<!--- Get a list of all the column names in the table mapped to the `author` model --->
<cfset columns = model("author").columnNames()>
Suggest Edits

columns()

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

 
columns()
<!--- Get the columns names in the order they are in the database --->
<cfset employee = model("employee").columns()>
Suggest Edits

exists()

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.

 
Parameter
Type
Required
Default
Description

key

any

false

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

false

This argument maps to the WHERE clause of the query. 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. Instead of using the where argument, you can create cleaner code by making use of a concept called Dynamic Finders.

reload

boolean

false

false

Set to true to force CFWheels to query the database even though an identical query may have been run in the same request. (The default in CFWheels is to get the second query from the request-level cache.)

parameterize

any

false

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

false

false

You can set this argument to true to include soft-deleted records in the results.

// 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();
Suggest Edits

findAll()

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).

 
Parameter
Type
Required
Default
Description

where

string

No

This argument maps to the WHERE clause of the query. 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. Instead of using the where argument, you can create cleaner code by making use of a concept called Dynamic Finders.

order

string

No

Maps to the ORDER BY clause of the query. You do not need to specify the table name(s); Wheels 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, Wheels 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. Wheels 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, count, and handle 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 Wheels 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 in pagination. This is useful when you're paginating multiple queries and need to reference them in the paginationLinks() function, for example. This argument is only used when the page argument has been passed in.

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 may have been run in the same request. (The default in CFWheels is to get the second query from the 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

You can set this argument to false to prevent running the execution of callbacks for a method call.

includeSoftDeletes

boolean

No

false

You can set this argument to true to include soft-deleted records in the results.

<!--- Getting only 5 users and ordering them randomly --->
<cfset 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)
--->
<cfset 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)
--->
<cfset 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)
--->
<cfset 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#")
--->
<cfset 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#'"
  )
--->
<cfset 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)
--->
<cfset post = model("post").findByKey(params.postId)>
<cfset comments = post.comments()>
Suggest Edits

findAllKeys()

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

 
Parameter
Type
Required
Default
Description

quoted

boolean

false

false

Set to true to enclose each value in single-quotation marks.

delimiter

string

false

,

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");
Suggest Edits

findByKey()

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().

 
Parameter
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, Wheels 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.

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 Wheels to query the database even though an identical query may have been run in the same request. (The default in Wheels is to get the second query from the 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 this to objects to return an array of objects. Set this to query to return a query result set.

callbacks

boolean

No

true

You can set this argument to false to prevent running the execution of callbacks for a method call.

includeSoftDeletes

boolean

No

false

You can set this argument to true to include soft-deleted records in the results.

<!--- Getting the author with the primary key value `99` as an object --->
<cfset auth = model("author").findByKey(99)>

<!--- Getting an author based on a form/URL value and then checking if it was found --->
<cfset auth = model("author").findByKey(params.key)>
<cfif NOT IsObject(auth)>
    <cfset flashInsert(message="Author #params.key# was not found")>
    <cfset redirectTo(back=true)>
</cfif>

<!--- 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) --->
<cfset comment = model("comment").findByKey(params.commentId)>
<cfset post = comment.post()>
Suggest Edits

findFirst()

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

 
Parameter
Type
Required
Default
Description

property

string

false

Name of the property to order by. This argument is also aliased as properties.

Suggest Edits

findLast()

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

 
Parameter
Type
Required
Default
Description

property

string

false

See documentation for findFirst.

Suggest Edits

findOne()

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.

 
findOne([ where, order, select, include, cache, reload, parameterize, returnAs, includeSoftDeletes ])
Parameter
Type
Required
Default
Description

key

any

Yes

This argument maps to the WHERE clause of the query. 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); Wheels 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); Wheels 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, Wheels 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.

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 Wheels to query the database even though an identical query may have been run in the same request. (The default in Wheels is to get the second query from the 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 this to objects to return an array of objects. Set this to query to return a query result set.

includeSoftDeletes

boolean

No

false

You can set this argument to true to include soft-deleted records in the results.

<!--- Getting the most recent order as an object from the database --->
<cfset 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'")` --->
<cfset 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'")` --->
<cfset 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) --->
<cfset user = model("user").findByKey(params.userId)>
<cfset 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) --->
<cfset post = model("post").findByKey(params.postId)>
<cfset comment = post.findOneComment(where="text='I Love Wheels!'")>
Suggest Edits

findOrCreateBy[Property]()

Returns the object or creates a new one if it wasn't found.

 
Parameter
Type
Required
Default
Description

save

boolean

false

true

Passing in false will create the object without saving it to the database.

// Return the first object that matches "Timberlake" in the last name column. If there is no match, create a new one and set firstName to "Justin".
newArtist = model("artist").findOrCreateByLastName(lastName="Timberlake", firstName="Justin");
Suggest Edits

getTableNamePrefix()

Returns the table name prefix set for the table.

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

invokeWithTransaction()

Runs the specified method within a single database transaction.

 
invokeWithTransaction(method [, transaction, isolation ])
Parameter
Type
Required
Default
Description

method

string

Yes

Model method to run.

transaction

string

No

commit

Set this to commit to update the database when the save has completed, 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 --->
<cffunction name="transferFunds" returntype="boolean" output="false">
    <cfargument name="personFrom">
    <cfargument name="personTo">
    <cfargument name="amount">
    <cfif arguments.personFrom.withdraw(arguments.amount) and arguments.personTo.deposit(arguments.amount)>
        <cfreturn true>
    <cfelse>
        <cfreturn false>
    </cfif>
</cffunction>

<cfset david = model("Person").findOneByName("David")>
<cfset mary = model("Person").findOneByName("Mary")>
<cfset invokeWithTransaction(method="transferFunds", personFrom=david, personTo=mary, amount=100)>
Suggest Edits

maximum()

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.

 
Parameter
Type
Required
Default
Description

property

string

true

Name of the property to get the highest value for (must be a property of a numeric data type).

where

string

false

See documentation for findAll.

include

string

false

See documentation for findAll.

parameterize

any

false

true

See documentation for findAll.

ifNull

any

false

See documentation for average.

includeSoftDeletes

boolean

false

false

See documentation for findAll.

group

string

false

See documentation for findAll.

// 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);
Suggest Edits

minimum()

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.

 
Parameter
Type
Required
Default
Description

property

string

true

Name of the property to get the lowest value for (must be a property of a numeric data type).

where

string

false

See documentation for findAll.

include

string

false

See documentation for findAll.

parameterize

any

false

true

See documentation for findAll.

ifNull

any

false

See documentation for average.

includeSoftDeletes

boolean

false

false

See documentation for findAll.

group

string

false

See documentation for findAll.

// 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);
Suggest Edits

new()

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.

 
Parameter
Type
Required
Default
Description

properties

struct

false

The properties you want to set on the object (can also be passed in as named arguments).

callbacks

boolean

false

true

See documentation for save.

<!--- Create a new author in memory (not saved to the database) --->
<cfset newAuthor = model("author").new()>

<!--- Create a new author based on properties in a struct --->
<cfset newAuthor = model("author").new(params.authorStruct)>

<!--- Create a new author by passing in named arguments --->
<cfset 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.) --->
<cfset aCustomer = model("customer").findByKey(params.customerId)>
<cfset anOrder = aCustomer.newOrder(shipping=params.shipping)>
Suggest Edits

primaryKey()

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().

 
primaryKey([ position ])
Parameter
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) --->
<cfset keyName = model("employee").primaryKey()>
Suggest Edits

primaryKeys()

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

 
primaryKeys([ position ])
Parameter
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) --->
<cfset keyNames = model("employee").primaryKeys()>
Suggest Edits

propertyNames()

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 Wheels ORM.

 
propertyNames()
<!--- Get a list of the property names in use in the user model --->
<cfset propNames = model("user").propertyNames()>
Suggest Edits

sum()

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.

 
Parameter
Type
Required
Default
Description

property

string

true

Name of the property to get the sum for (must be a property of a numeric data type).

where

string

false

This argument maps to the WHERE clause of the query. 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. Instead of using the where argument, you can create cleaner code by making use of a concept called Dynamic Finders.

include

string

false

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

false

false

When true, SUM returns the sum of unique values only.

parameterize

any

false

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

false

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

false

false

You can set this argument to true to include soft-deleted records in the results.

group

string

false

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);
Suggest Edits

tableName()

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

 
tableName()
<!--- Check what table the user model uses --->
<cfset whatAmIMappedTo = model("user").tableName()>
Suggest Edits

updateAll()

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.

 
updateAll([ where, include, properties, reload, parameterize, instantiate, validate, transaction, callbacks, includeSoftDeletes ])
Parameter
Type
Required
Default
Description

where

string

No

This argument maps to the WHERE clause of the query. 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); Wheels 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 Wheels to query the database even though an identical query may have been run in the same request. (The default in Wheels is to get the second query from the 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

Set to false to skip validations for this operation.

transaction

string

No

[runtime expression]

Set this to commit to update the database when the save has completed, 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 operation.

includeSoftDeletes

boolean

No

false

You can set this argument to true to include soft-deleted records in the results.

<!---
  Update the `published` and `publishedAt` properties for all records that have
  `published=0`
--->
<cfset 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.)
--->
<cfset post = model("post").findByKey(params.postId)>
<cfset post.removeAllComments()>
Suggest Edits

updateByKey()

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.

 
updateByKey(key [, properties, reload, validate, transaction, callbacks, includeSoftDeletes ])
Parameter
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 Wheels to query the database even though an identical query may have been run in the same request. (The default in Wheels is to get the second query from the 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 when the save has completed, 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 operation.

includeSoftDeletes

boolean

No

false

You can set this argument to true to include soft-deleted records in the results.

<!--- Updates the object with `33` as the primary key value with values passed in through the URL/form --->
<cfset result = model("post").updateByKey(33, params.post)>

<!--- Updates the object with `33` as the primary key using named arguments --->
<cfset result = model("post").updateByKey(key=33, title="New version of Wheels just released", published=1)>
Suggest Edits

updateOne()

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.

 
updateOne([ where, order, properties, reload, validate, transaction, callbacks, includeSoftDeletes ])
Parameter
Type
Required
Default
Description

where

string

No

This argument maps to the WHERE clause of the query. 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); Wheels 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); Wheels 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 Wheels to query the database even though an identical query may have been run in the same request. (The default in Wheels is to get the second query from the request-level cache.)

validate

transaction

string

No

[runtime expression]

Set this to commit to update the database when the save has completed, 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 operation.

includeSoftDeletes

boolean

No

false

You can set this argument to true to include soft-deleted records in the results.

<!--- Sets the `new` property to `1` on the most recently released product --->
<cfset 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.) --->
<cfset aUser = model("user").findByKey(params.userId)>
<cfset aUser.removeProfile()>
Suggest Edits

updateProperties()

Updates all the properties from the properties argument or other named arguments. If the object is invalid, the save will fail and false will be returned.

 
updateProperties([ properties, parameterize, validate, transaction, callbacks ])
Parameter
Type
Required
Default
Description

properties

struct

No

[runtime expression]

Struct containing key/value pairs with properties and associated values that need to be updated 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.

validate

boolean

No

Set to false to skip validations for this operation.

transaction

string

No

[runtime expression]

Set this to commit to update the database when the save has completed, 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 operation.

<!--- Sets the `new` property to `1` through `updateProperties()` --->
<cfset product = model("product").findByKey(56)>
<cfset product.updateProperties(new=1)>
Suggest Edits

updateProperty()

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.

 
updateProperty(property, value [, parameterize, transaction, callbacks ])
Parameter
Type
Required
Default
Description

property

string

Yes

Name of the property to update the value for globally.

value

any

Yes

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 when the save has completed, 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 operation.

<!--- Sets the `new` property to `1` through updateProperty() --->
<cfset product = model("product").findByKey(56)>
<cfset product.updateProperty("new", 1)>
Suggest Edits

validationTypeForProperty()

Returns the validation type for the property

 
validationTypeForProperty(property)
Parameter
Type
Required
Default
Description

property

string

Yes

Name of column to retrieve data for.

<!--- first name is a varchar(50) column --->
<cfset employee = model("employee").new()>
<!--- would output "string" --->
<cfoutput>#employee.validationTypeForProperty("firstName")>#</cfoutput>
Suggest Edits

Model Object Functions

These methods operate on individual objects, which means you first need to fetch or create an object and then call the method on that object. You can call these methods from anywhere, but it is not recommended to call them from view pages. When calling them from their own model files, it is recommended to reference them explicitly with the this scope keyword.

 
Suggest Edits

allChanges()

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

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

changedFrom()

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

 
changedFrom(property)
Parameter
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 --->
<cfset member = model("member").findByKey(params.memberId)>
<cfset member.email = params.newEmail>

<!--- Get the previous value (what the `email` property was before it was changed)--->
<cfset oldValue = member.changedFrom("email")>

<!--- The above can also be done using a dynamic function like this --->
<cfset oldValue = member.emailChangedFrom()>
Suggest Edits

changedProperties()

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

 
changedProperties()
<!--- 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) --->
<cfset member = model("member").findByKey(params.memberId)>
<cfset member.firstName = params.newFirstName>
<cfset member.email = params.newEmail>
<cfset changedProperties = member.changedProperties()>
Suggest Edits

clearChangeInformation()

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

 
Parameter
Type
Required
Default
Description

property

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();
Suggest Edits

hasChanged()

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.

 
hasChanged([ property ])
Parameter
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 --->
<cfset member = model("member").findByKey(params.memberId)>
<cfset member.email = params.newEmail>

<!--- Check if the `email` property has changed --->
<cfif member.hasChanged("email")>
    <!--- Do something... --->
</cfif>

<!--- The above can also be done using a dynamic function like this --->
<cfif member.emailHasChanged()>
    <!--- Do something... --->
</cfif>
Suggest Edits

delete()

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.

 
delete([ parameterize, transaction, callbacks, includeSoftDeletes, softDelete ])
Parameter
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 when the save has completed, 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 operation.

includeSoftDeletes

boolean

No

false

You can set this argument to true to include soft-deleted records in the results.

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 --->
<cfset post = model("post").findByKey(33)>
<cfset 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.) --->
<cfset post = model("post").findByKey(params.postId)>
<cfset comment = model("comment").findByKey(params.commentId)>
<cfset post.deleteComment(comment)>
Suggest Edits

save()

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

 
Parameter
Type
Required
Default
Description

parameterize

any

false

true

See documentation for findAll.

reload

boolean

false

false

Set to true to reload the object from the database once an insert/update has completed.

validate

boolean

false

true

Set to false to skip validations for this operation.

transaction

string

false

Set this to commit to update the database when the save has completed, rollback to run all the database queries but not commit them, or none to skip transaction handling altogether.

callbacks

boolean

false

true

Set to false to disable callbacks for this operation.

<!--- 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 --->
<cfset user.save()>

<!--- Save the user object directly in an if statement without using `cfqueryparam` and take appropriate action based on the result --->
<cfif user.save(parameterize=false)>
	<cfset flashInsert(notice="The user was saved!")>
	<cfset redirectTo(action="edit")>
<cfelse>
	<cfset flashInsert(alert="Error, please correct!")>
	<cfset renderPage(action="edit")>
</cfif>
Suggest Edits

toggle()

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.

 
toggle([ save ])
Parameter
Type
Required
Default
Description

save

boolean

No

true

Argument to decide whether save the property after it has been toggled. Defaults to true.

<!--- Get an object, and toggle a boolean property --->
<cfset user = model("user").findByKey(58)>
<cfset isSuccess = user.toggle("isActive")><!--- returns whether the object was saved properly --->
<!--- You can also use a dynamic helper for this --->
<cfset isSuccess = user.toggleIsActive()>
Suggest Edits

update()

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.

 
update([ properties, parameterize, reload, validate, transaction, callbacks ])
Parameter
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 Wheels to query the database even though an identical query may have been run in the same request. (The default in Wheels is to get the second query from the request-level cache.)

validate

boolean

No

true

Set to false to skip validations for this operation.

transcation

string

No

[runtime expression]

Set this to commit to update the database when the save has completed, 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 operation.

<!--- Get a post object and then update its title in the database --->
<cfset post = model("post").findByKey(33)>
<cfset 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 --->
<cfset post = model("post").findByKey(params.key)>
<cfset 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.) --->
<cfset author = model("author").findByKey(params.authorId)>
<cfset bio = model("bio").findByKey(params.bioId)>
<cfset 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.) --->
<cfset anOwner = model("owner").findByKey(params.ownerId)>
<cfset aCar = model("car").findByKey(params.carId)>
<cfset 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.) --->
<cfset aPost = model("post").findByKey(params.postId)>
<cfset aComment = model("comment").findByKey(params.commentId)>
<cfset aPost.removeComment(aComment)><!--- Get an object, and toggle a boolean property --->
<cfset user = model("user").findByKey(58)>
<cfset isSuccess = user.toggle("isActive")><!--- returns whether the object was saved properly --->
<!--- You can also use a dynamic helper for this --->
<cfset isSuccess = user.toggleIsActive()>
Suggest Edits

addError()

Adds an error on a specific property.

 
addError(property, message [, name ])
Parameter
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 --->
<cfset this.addError(property="email", message="Sorry, you are not allowed to use that email. Try again, please.")>
Suggest Edits

addErrorToBase()

Adds an error on a specific property.

 
Adds an error on the object as a whole (not related to any specific property).
Parameter
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 --->
<cfset this.addErrorToBase(message="Your email address must be the same as your domain name.")>
Suggest Edits

allErrors()

Returns an array of all the errors on the object.

 
allErrors()
<!--- Get all the errors for the `user` object --->
<cfset errorInfo = user.allErrors()>
<!--- Sample Return of Function --->
[
	{
  	message:'Username must not be blank',
    name:'usernameError',
    property:'username'
  },
  {
  	message:'Password must not be blank',
    name:'passwordError',
    property:'password'
  }
]
Suggest Edits

clearErrors()

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

 
clearErrors([ property, name ])
Parameter
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 --->
<cfset this.clearErrors()>

<!--- Clear all errors on `firstName` --->
<cfset this.clearErrors("firstName")>
Suggest Edits

errorCount()

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

 
errorCount([ property, name ])
Parameter
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 --->
<cfif author.errorCount() GTE 10>
    <!--- Do something to deal with this very erroneous author here... --->
</cfif>

<!--- Check how many errors are associated with the `email` property --->
<cfif author.errorCount("email") gt 0>
    <!--- Do something to deal with this erroneous author here... --->
</cfif>
Suggest Edits

errorsOn()

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

 
errorsOn(property [, name ])
Parameter
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 above property set with a specific error name you can specify it here.

<!--- Get all errors related to the email address of the user object --->
<cfset errors = user.errorsOn("emailAddress")>
Suggest Edits

errorsOnBase()

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

 
errorsOnBase([ name ])
Parameter
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 --->
<cfset errors = user.errorsOnBase()>
Suggest Edits

hasErrors()

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

 
hasErrors([ property, name ])
Parameter
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 --->
<cfif post.hasErrors()>
    <!--- Send user to a form to correct the errors... --->
</cfif>
Suggest Edits

valid()

Runs the validation on the object and returns true if it passes it. Wheels 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.

 
Parameter
Type
Required
Default
Description

callbacks

boolean

false

true

Set to false to disable callbacks for this operation.

<!--- Check if a user is valid before proceeding with execution --->
<cfset user = model("user").new(params.user)>
<cfif user.valid()>
    <!--- Do something here --->
</cfif>
Suggest Edits

compareTo()

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

 
compareTo()
<!--- Load a user requested in the URL/form and restrict access if it doesn't match the user stored in the session --->
<cfset user = model("user").findByKey(params.key)>
<cfif not user.compareTo(session.user)>
    <cfset renderPage(action="accessDenied")>
</cfif>
Suggest Edits

hasProperty()

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

 
hasProperty(property)
Parameter
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 --->
<cfset employee = model("employee").new()>
<cfset employee.firstName = "dude">
<cfset employee.hasProperty("firstName")><!--- returns true --->

<!--- This is also a dynamic method that you could do --->
<cfset employee.hasFirstName()>
Suggest Edits

isNew()

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.

 
isNew()
<!--- 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) --->
<cfset employee = model("employee").new()>
<cfif employee.isNew()>
    <!--- Do something... --->
</cfif>
Suggest Edits

key()

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).

 
key()
<!--- Get an object and then get the primary key value(s) --->
<cfset employee = model("employee").findByKey(params.key)>
<cfset val = employee.key()>
Suggest Edits

properties()

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

 
properties()
<!--- Get a structure of all the properties for an object --->
<cfset user = model("user").findByKey(1)>
<cfset props = user.properties()>
Suggest Edits

propertyIsPresent()

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

 
propertyIsPresent(property)
Parameter
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 --->
<cfset employee = model("employee").new()>
<cfset employee.firstName = "dude">
<cfreturn employee.propertyIsPresent("firstName")><!--- Returns true --->

<cfset employee.firstName = "">
<cfreturn employee.propertyIsPresent("firstName")><!--- Returns false --->
Suggest Edits

reload()

Reloads the property values of this object from the database.

 
reload()
<!--- Get an object, call a method on it that could potentially change values, and then reload the values from the database --->
<cfset employee = model("employee").findByKey(params.key)>
<cfset employee.someCallThatChangesValuesInTheDatabase()>
<cfset employee.reload()>
Suggest Edits

setProperties()

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

 
setProperties([ properties ])
Parameter
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 --->
<cfset user = model("user").findByKey(1)>
<cfset user.setProperties(params.user)>
Suggest Edits

buttonTag()

Builds and returns a string containing a button form control.

 
Parameter
Type
Required
Default
Description

content

string

false

Save changes

Content to display inside the button.

type

string

false

submit

The type for the button: button, reset, or submit.

value

string

false

save

The value of the button when submitted.

image

string

false

File name of the image file to use in the button form control.

disable

any

false

Whether or not to disable the button upon clicking (prevents double-clicking).

prepend

string

false

See documentation for textField

append

string

false

See documentation for textField

<!--- view code --->
<cfoutput>
    #startFormTag(action="something")#
        <!--- form controls go here --->
        #buttonTag(content="Submit this form", value="save")#
    #endFormTag()#
</cfoutput>
Suggest Edits

buttonTo()

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

 
Parameter
Type
Required
Default
Description

text

string

false

The text content of the button.

confirm

string

false

See documentation for linkTo.

image

string

false

If you want to use an image for the button pass in the link to it here (relative from the images folder).

disable

any

false

Pass in true if you want the button to be disabled when clicked (can help prevent multiple clicks), or pass in a string if you want the button disabled and the text on the button updated (to "please wait...", for example).

route

string

false

See documentation for URLFor.

controller

string

false

See documentation for URLFor.

action

string

false

See documentation for URLFor.

key

any

false

See documentation for URLFor.

params

string

false

See documentation for URLFor.

anchor

string

false

See documentation for URLFor.

onlyPath

boolean

false

true

See documentation for URLFor.

host

string

false

See documentation for URLFor.

protocol

string

false

See documentation for URLFor.

port

numeric

false

0

See documentation for URLFor.

#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")#
Suggest Edits

checkBoxTag()

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.

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

checked

boolean

false

false

Whether or not the check box should be checked by default.

value

string

false

1

Value of check box in its checked state.

uncheckedValue

string

false

The value of the check box when it's on the unchecked state.

label

string

false

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

<!--- Example 1: Basic usage involves a `label`, `name`, and `value` --->
<cfoutput>
    #checkBoxTag(name="subscribe", value="true", label="Subscribe to our newsletter", checked=false)#
</cfoutput>

<!--- Example 2: Loop over a query to display choices and whether or not they are checked --->
<!--- - Controller code --->
<cfset pizza = model("pizza").findByKey(session.pizzaId)>
<cfset selectedToppings = pizza.toppings()>
<cfset 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>
Suggest Edits

contentFor()

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.

 
Parameter
Type
Required
Default
Description

position

any

false

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

false

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>
Suggest Edits

contentForLayout()

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

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

cycle()

Cycles through list values every time it is called.

 
Parameter
Type
Required
Default
Description

values

string

true

List of values to cycle through.

name

string

false

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>
				<cfset rank = cycle(values="president,vice-president,director,manager,specialist,intern", name="position")>
				<li class="##rank##">##categories.categoryName##</li>
				<cfset resetCycle("emphasis")>
			</cfoutput>
		</ul>
	</div>
</cfoutput>
Suggest Edits

dateSelectTags()

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

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

selected

string

false

See documentation for selectTag.

order

string

false

month, day, year

See documentation for dateSelect.

separator

string

false

See documentation for dateSelect.

startYear

numeric

false

2010

See documentation for dateSelect.

endYear

numeric

false

2020

See documentation for dateSelect.

monthDisplay

string

false

names

See documentation for dateSelect.

monthNames

string

false

January, February, March, April, May, June, July, August, September, October, November, December

See documentation for dateSelect.

monthAbbreviations

string

false

Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec

See documentation for dateSelect.

includeBlank

any

false

false

See documentation for select.

label

string

false

See documentation for dateSelect.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

combine

boolean

false

See documentation for dateSelect.

<!--- This "Tag" version of function accepts `name` and `selected` instead of binding to a model object --->
<cfoutput>
	#dateSelectTags(name="dateStart", selected=params.dateStart)#
</cfoutput>

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

dateTimeSelectTags()

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.

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

selected

string

false

See documentation for selectTag.

dateOrder

string

false

month,day,year

See documentation for dateTimeSelect.

dateSeparator

string

false

See documentation for dateTimeSelect.

startYear

numeric

false

2010

See documentation for dateSelect.

endYear

numeric

false

2020

See documentation for dateSelect.

monthDisplay

string

false

names

See documentation for dateSelect.

monthNames

string

false

January,February,March,April,May,June,July,August,September,October,November,December

See documentation for dateSelect.

monthAbbreviations

string

false

Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec

See documentation for dateSelect.

timeOrder

string

false

hour,minute,second

See documentation for dateTimeSelect.

timeSeparator

string

false

:

See documentation for dateTimeSelect.

minuteStep

numeric

false

1

See documentation for timeSelect.

secondStep

numeric

false

1

See documentation for timeSelect.

separator

string

false

-

See documentation for dateTimeSelect.

includeBlank

any

false

false

See documentation for select.

label

string

false

See documentation for dateSelect.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

combine

boolean

false

See documentation for dateSelect.

twelveHour

boolean

false

false

See documentation for timeSelect.

<!--- This "Tag" version of the function accepts a `name` and `selected` instead of binding to a model object --->
<cfoutput>
    #dateTimeSelectTags(name="dateTimeStart", selected=params.dateTimeStart)#
</cfoutput>

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

distanceOfTimeInWords()

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

 

Function Syntax

distanceOfTimeInWords(fromTime, toTime [, includeSeconds ])

Parameters

Parameter
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.

Examples

<cfset aWhileAgo = Now() - 30>
<cfset rightNow = Now()>
<cfoutput>#distanceOfTimeInWords(aWhileAgo, rightNow)#</cfoutput>
Suggest Edits

endFormTag()

Builds and returns a string containing the closing form tag.

 
Parameter
Type
Required
Default
Description

prepend

string

false

See documentation for textField

append

string

false

See documentation for textField

		<!--- view code --->
		<cfoutput>
		    #startFormTag(action="create")#
		        <!--- your form controls --->
		    #endFormTag()#
		</cfoutput>
Suggest Edits

errorMessageOn()

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

 
errorMessageOn(objectName, property [, prependText, appendText, wrapperElement, class ])
Parameter
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

errorMessage

CSS class to set on the wrapper element.

<!--- view code --->
<cfoutput>
  #errorMessageOn(objectName="user", property="email")#
</cfoutput>
Suggest Edits

errorMessagesFor()

Builds and returns a list (ul tag with a default class of errorMessages) containing all the error messages for all the properties of the object (if any). Returns an empty string otherwise.

 
errorMessagesFor(objectName [, class, showDuplicates ])
Parameter
Type
Required
Default
Description

objectName

string

Yes

The variable name of the object to display error messages for.

class

string

No

errorMessage

CSS class to set on the ul element.

showDuplicates

boolean

No

true

Whether or not to show duplicate error messages.

<!--- view code --->
<cfoutput>
    #errorMessagesFor(objectName="user")#
</cfoutput>
Suggest Edits

excerpt()

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

 
Parameter
Type
Required
Default
Description

text

string

true

The text to extract an excerpt from.

phrase

string

true

The phrase to extract.

radius

numeric

false

100

Number of characters to extract surrounding the phrase.

excerptString

string

false

...

String to replace first and/or last characters with.

#excerpt(text="ColdFusion CFWheels is a Rails-like MVC framework for Adobe ColdFusion, Railo and Lucee", phrase="framework", radius=5)#
-> ... MVC framework for ...
Suggest Edits

flashMessages()

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

 
Parameter
Type
Required
Default
Description

keys

string

false

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

false

flashMessages

HTML class to set on the div element that contains the messages.

includeEmptyContainer

boolean

false

false

Includes the div container even if the Flash is empty.

lowerCaseDynamicClassValues

boolean

false

false

Outputs all class attribute values in lower case (except the main one).

<!--- 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 --->
<cfoutput>
	#flashMessages()#
</cfoutput>
<!---
	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 --->
<cfoutput>
	#flashMessages(key="success")#
</cfoutput>
<!---
	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 --->
<cfoutput>
	#flashMessages(keys="success,alert")#
</cfoutput>
<!---
	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>
--->
Suggest Edits

hasManyCheckBox()

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.

 
hasManyCheckBox(objectName, association, keys [, label, labelPlacement, prepend, append, prependToLabel, appendToLabel, errorElement, errorClass ])
Parameter
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.

<!--- 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>
Suggest Edits

hasManyRadioButton()

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.

 
hasManyRadioButton(objectName, association, property, keys, tagValue [, checkIfBlank, label ])
Parameter
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.

<!--- 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>
Suggest Edits

highlight()

Highlights the phrase(s) everywhere in the text if found by wrapping it in a span tag.

 
Parameter
Type
Required
Default
Description

text

string

true

Text to search.

phrases

string

true

List of phrases to highlight.

delimiter

string

false

,

Delimiter to use in phrases argument.

tag

string

false

span

HTML tag to use to wrap the highlighted phrase(s).

class

string

false

highlight

Class to use in the tags wrapping highlighted phrase(s).

#highlight(text="You searched for: Wheels", phrases="Wheels")#
-> You searched for: <span class="highlight">Wheels</span>
Suggest Edits

imageTag()

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. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

 

Function Syntax

imageTag(source)

Parameters

Parameter
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.

Examples

<!--- 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")#
Suggest Edits

includeContent()

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

 
Parameter
Type
Required
Default
Description

name

string

false

body

Name of layout section to return content for.

defaultValue

string

false

What to display as a default if the section is not defined.

<!--- In your view template, let''s say `views/blog/post.cfm --->
<cfset contentFor(head=''<meta name="robots" content="noindex,nofollow">"'')>
<cfset 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>
Suggest Edits

includedInObject()

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.

 
includedInObject(objectName, association, keys)
Parameter
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 --->
<cfif not includedInObject(objectName="customer", association="subscriptions", keys="#customer.key()#,#swimsuitEdition.id#")>
    <cfset assignSalesman(customer)>
</cfif>
Suggest Edits

checkBox()

Builds and returns a string containing a check box form control based on the supplied objectName and property. In most cases, this function generates a form field that should represent a boolean style field in your data. Use checkBoxTag() or hasManyCheckBox() to generate check boxes for selecting multiple values. Note: Pass any additional arguments like class, rel, and id, and the generated tag will also include those values as HTML attributes.

 
checkBox(objectName, property [, association, position, checkedValue, uncheckedValue, label, labelPlacement, prepend, append, prependToLabel, appendToLabel, errorElement, errorClass ])
Parameter
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 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.

checkedValue

string

No

1

The value of the check box when it's in the checked state.

uncheckedValue

string

No

0

The value of the check box when it's in 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

fieldWithErrors

The class name of the HTML tag that wraps the form control when there are errors.

<!--- Basic example of a check box for a boolean field --->
<cfoutput>
    #checkBox(objectName="photo", property="isPublic", label="Display this photo publicly.")#
</cfoutput>

<!--- Shows check boxes for selecting public access for all photos provided by the `photos` association and nested properties --->
<cfoutput>
    <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>
</cfoutput>
Suggest Edits

dateSelect()

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

 
dateSelect([ objectName, property, association, position, order, separator, startYear, endYear, monthDisplay, includeBlank, label, labelPlacement, prepend, append, prependToLabel, appendToLabel, errorElement, errorClass, combine ])
Parameter
Type
Required
Default
Description

objectName

any

No

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.

order

string

No

month,day,year

Use to change the order of or exclude date select tags.

seperator

string

No

Use to change the character that is displayed between the date select tags.

startYear

numeric

No

2009

First year in select list.

endYear

numeric

No

2019

Last year in select list.

monthDisplay

string

No

names

Pass in names, numbers, or abbreviations to control display.

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

fieldWithErrors

The class name of the HTML tag that wraps the form control when there are errors.

combine

boolean

No

<!--- View code --->
<cfoutput>
    #dateSelect(objectName="user", property="dateOfBirth")#
</cfoutput>

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

dateTimeSelect()

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.

 
dateTimeSelect(objectName, property [, association, position, dateOrder, dateSeparator, startYear, endYear, monthDisplay, timeOrder, timeSeparator, minuteStep, secondStep, separator, includeBlank, label, labelPlacement, prepend, append, prependToLabel, appendToLabel, errorElement, errorClass, combine, twelveHour ])
Parameter
Type
Required
Default
Description

objectName

any

No

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.

dateSeperator

string

No

Use to change the character that is displayed between the date select tags.

startYear

numeric

No

2009

First year in select list.

startYear

numeric

No

2019

Last year in select list.

monthDisplay

string

No

names

Pass in names, numbers, or abbreviations to control display.

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

fieldWithErrors

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

<!--- View code --->
<cfoutput>
    #dateTimeSelect(objectName="article", property="publishedAt")#
</cfoutput>

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

daySelectTag()

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

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

selected

string

false

The day that should be selected initially.

includeBlank

any

false

false

See documentation for select.

label

string

false

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

<!--- This "Tag" version of the function accepts a `name` and `selected` instead of binding to a model object --->
<cfoutput>
    #daySelectTag(name="dayOfWeek", selected=params.dayOfWeek)#
</cfoutput>
Suggest Edits

fileField()

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.

 
Parameter
Type
Required
Default
Description

objectName

any

true

See documentation for textField.

property

string

true

See documentation for textField.

association

string

false

See documentation for textfield.

position

string

false

See documentation for textfield.

label

string

false

useDefaultLabel

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

errorElement

string

false

span

See documentation for textField.

errorClass

string

false

fieldWithErrors

See documentation for textField.

<!--- Provide a `label` and the required `objectName` and `property` --->
<cfoutput>
    #fileField(label="Photo", objectName="photo", property="imageFile")#
</cfoutput>

<!--- 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>
Suggest Edits

fileFieldTag()

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.

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

label

string

false

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

<!--- Basic usage usually involves a `label`, `name`, and `value` --->
<cfoutput>
    #fileFieldTag(label="Photo", name="photo", value=params.photo)#
</cfoutput>
Suggest Edits

hiddenField()

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.

 
Parameter
Type
Required
Default
Description

objectName

any

true

See documentation for textField.

property

string

true

See documentation for textField.

association

string

false

See documentation for textfield.

position

string

false

See documentation for textfield.

<!--- Provide an `objectName` and `property` --->
<cfoutput>
    #hiddenField(objectName="user", property="id")#
</cfoutput>
Suggest Edits

hiddenFieldTag()

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.

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

value

string

false

See documentation for textFieldTag.

<!--- Basic usage usually involves a `name` and `value` --->
<cfoutput>
    #hiddenFieldTag(name="userId", value=user.id)#
</cfoutput>
Suggest Edits

hourSelectTag()

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

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

selected

string

false

The hour that should be selected initially.

includeBlank

any

false

false

See documentation for select.

label

string

false

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

twelveHour

boolean

false

false

See documentation for timeSelect.

<!--- This "Tag" version of the function accepts a `name` and `selected` instead of binding to a model object --->
<cfoutput>
    #hourSelectTag(name="hourOfMeeting", selected=params.hourOfMeeting)#
</cfoutput>

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

includeLayout()

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

 
Parameter
Type
Required
Default
Description

name

string

false

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>
<cfset contentFor(sidebar=categoriesSidebar)>

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

includePartial()

Includes the specified partial file in the view. Similar to using cfinclude but with the ability to cache the result and use Wheels-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 name with a forward slash.

 
Parameter
Type
Required
Default
Description

partial

any

true

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

false

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

false

Number of minutes to cache the content for.

layout

string

false

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

false

HTML or string to place between partials when called using a query.

dataFunction

any

false

true

Name of controller function to load data from.

query

query

false

If you want to have CFWheels display the partial for each record in a query record set but want to override the name of the file referenced, provide the template file name for partial and pass the query as a separate query argument.

object

component

false

If you want to have CFWheels display the partial for a model object but want to override the name of the file referenced, provide the template file name for partial and pass the model object as a separate object argument.

objects

array

false

If you want to have CFWheels display the partial for each model object in an array but want to override the name of the file referenced, provide the template name for partial and pass the query as a separate objects argument.

<cfoutput>

<!---
    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>
Suggest Edits

javaScriptIncludeTag()

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

 

Function Syntax

javaScriptIncludeTag([ sources, type, head, delim ])

Parameters

Parameter
Type
Required
Default
Description

sources

string

No

The name of one or many JavaScript files in the javascripts folder, minus the .js extension. (Can also be called with the source argument.) Pass a full URL to access an external JavaScript file.

type

string

No

The type attribute for the script tag.

head

string

No

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 javascripts

Examples

<!--- 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>
Suggest Edits

linkTo()

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.

 
Parameter
Type
Required
Default
Description

text

string

false

The text content of the link.

confirm

string

false

Pass a message here to cause a JavaScript confirmation dialog box to pop up containing the message.

route

string

false

Name of a route that you have configured in config/routes.cfm.

controller

string

false

Name of the controller to include in the URL.

action

string

false

Name of the action to include in the URL.

key

any

false

Key(s) to include in the URL.

params

string

false

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 (using URLEncodedFormat() internally). 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

false

Sets an anchor name to be appended to the path.

onlyPath

boolean

false

true

If true, returns only the relative URL (no protocol, host name or port).

host

string

false

Set this to override the current host.

protocol

string

false

Set this to override the current protocol.

port

numeric

false

0

Set this to override the current port number.

href

string

false

Pass a link to an external site here if you want to bypass the CFWheels routing system altogether and link to an external URL.

#linkTo(text="Log Out", controller="account", action="logout")#
-> <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")#
-> <a href="/account/logout">Log Out</a>

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

#linkTo(text="View Settings", action="settings", params="show=all&sort=asc")#
-> <a href="/account/settings?show=all&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")#
-> <a href="/user/joe">Joe's Profile</a>

<!--- Link to an external website --->
#linkTo(text="ColdFusion Framework", href="http://cfwheels.org/")#
-> <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")#
-> <a class="delete" href="/blog/delete/99" id="delete-99">Delete Post</a>
Suggest Edits

mailTo()

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

 
Parameter
Type
Required
Default
Description

emailAddress

string

true

The email address to link to.

name

string

false

A string to use as the link text ("Joe" or "Support Department", for example).

encode

boolean

false

false

Pass true here to encode the email address, making it harder for bots to harvest it for example.

#mailTo(emailAddress="[email protected]", name="Contact our Webmaster")#
-> <a href="mailto:[email protected]">Contact our Webmaster</a>
Suggest Edits

minuteSelectTag()

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

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

selected

string

false

The minute that should be selected initially.

minuteStep

numeric

false

1

See documentation for timeSelect.

includeBlank

any

false

false

See documentation for select.

label

string

false

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

<!--- 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>
Suggest Edits

monthSelectTag()

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

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

selected

string

false

The month that should be selected initially.

monthDisplay

string

false

names

See documentation for dateSelect.

monthNames

string

false

January,February,March,April,May,June,July,August,September,October,November,December

See documentation for dateSelect.

monthAbbreviations

string

false

Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec

See documentation for dateSelect.

includeBlank

any

false

false

See documentation for select.

label

string

false

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

<!--- 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>
Suggest Edits

passwordField()

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.

 
Parameter
Type
Required
Default
Description

objectName

any

true

See documentation for textField.

property

string

true

See documentation for textField.

association

string

false

See documentation for textfield.

position

string

false

See documentation for textfield.

label

string

false

useDefaultLabel

See documentation for textField

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

errorElement

string

false

span

See documentation for textField.

errorClass

string

false

fieldWithErrors

See documentation for textField.

<!--- 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>
Suggest Edits

passwordFieldTag()

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.

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

value

string

false

See documentation for textFieldTag.

label

string

false

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

<!--- Basic usage usually involves a `label`, `name`, and `value` --->
<cfoutput>
    #passwordFieldTag(label="Password", name="password", value=params.password)#
</cfoutput>
Suggest Edits

radioButton()

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.

 
Parameter
Type
Required
Default
Description

objectName

any

true

See documentation for textField.

property

string

true

See documentation for textField.

association

string

false

See documentation for textfield.

position

string

false

See documentation for textfield.

tagValue

string

true

The value of the radio button when selected.

label

string

false

useDefaultLabel

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

errorElement

string

false

span

See documentation for textField.

errorClass

string

false

fieldWithErrors

See documentation for textField.

<!--- 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>
Suggest Edits

radioButtonTag()

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.

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

value

string

true

See documentation for textFieldTag.

checked

boolean

false

false

Whether or not to check the radio button by default.

label

string

false

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

<!--- 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>
Suggest Edits

resetCycle()

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

 
Parameter
Type
Required
Default
Description

name

string

false

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>
				<cfset rank = cycle(values="president,vice-president,director,manager,specialist,intern", name="position")>
				<li class="#rank#">#categories.categoryName#</li>
				<cfset resetCycle("emphasis")>
			</cfoutput>
		</ul>
	</div>
</cfoutput>
Suggest Edits

secondSelectTag()

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

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

selected

string

false

The second that should be selected initially.

secondStep

numeric

false

1

See documentation for timeSelect.

includeBlank

any

false

false

See documentation for select.

label

string

false

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

<!--- This "Tag" version of the function accepts a `name` and `selected` instead of binding to a model object --->
<cfoutput>
    #secondSelectTag(name="secondsToLaunch", selected=params.secondsToLaunch)#
</cfoutput>

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

select()

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.

 
<!--- Example 1: Basic `select` field with `label` and required `objectName` and `property` arguments --->
<!--- - Controller code --->
<cfset authors = model("author").findAll()>

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

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

<!--- - View code --->
<cfoutput>
	<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>
</cfoutput>
Parameter
Type
Required
Default
Description

objectName

any

true

See documentation for textField.

property

string

true

See documentation for textField.

association

string

false

See documentation for textfield.

position

string

false

See documentation for textfield.

options

any

true

A collection to populate the select form control with. Can be a query recordset or an array of objects.

includeBlank

any

false

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

false

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.

textField

string

false

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.

label

string

false

useDefaultLabel

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

errorElement

string

false

span

See documentation for textField.

errorClass

string

false

fieldWithErrors

See documentation for textField.

Suggest Edits

selectTag()

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.

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

options

any

true

See documentation for select.

selected

string

false

Value of option that should be selected by default.

includeBlank

any

false

false

See documentation for select.

multiple

boolean

false

false

Whether to allow multiple selection of options in the select form control.

valueField

string

false

See documentation for select.

textField

string

false

See documentation for select.

label

string

false

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

<!--- Controller code --->
<cfset cities = model("city").findAll()>

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

<!--- Do this when CFWheels isn''t grabbing the correct values for the `option`s'' values and display texts --->
<cfoutput>
	#selectTag(name="cityId", options=cities, valueField="id", textField="name")#
</cfoutput>
Suggest Edits

simpleFormat()

Replaces single newline characters with HTML break tags and double newline characters with HTML paragraph tags (properly closed to comply with XHTML standards).

 
Parameter
Type
Required
Default
Description

text

string

true

The text to format.

wrap

boolean

false

true

Set to true to wrap the result in a paragraph.

<!--- 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>
Suggest Edits

startFormTag()

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.

 
Parameter
Type
Required
Default
Description

method

string

false

post

The type of method to use in the form tag. get and post are the options.

multipart

boolean

false

false

Set to true if the form should be able to upload files.

spamProtection

boolean

false

false

Set to true to protect the form against spammers (done with JavaScript).

route

string

false

Name of a route that you have configured in config/routes.cfm.

controller

string

false

Name of the controller to include in the URL.

action

string

false

Name of the action to include in the URL.

key

any

false

Key(s) to include in the URL.

params

string

false

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 (using URLEncodedFormat() internally). 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

false

Sets an anchor name to be appended to the path.

onlyPath

boolean

false

true

If true, returns only the relative URL (no protocol, host name or port).

host

string

false

Set this to override the current host.

protocol

string

false

Set this to override the current protocol.

port

numeric

false

0

Set this to override the current port number.

prepend

string

false

String to prepend to the form control. Useful to wrap the form control with HTML tags.

append

string

false

String to append to the form control. Useful to wrap the form control with HTML tags.

<!--- view code --->
<cfoutput>
    #startFormTag(action="create", spamProtection=true)#
        <!--- your form controls --->
    #endFormTag()#
</cfoutput>
Suggest Edits

stripTags()

Removes all HTML tags from a string.

 
Parameter
Type
Required
Default
Description

html

string

true

The HTML to remove tag markup from.

<!--- Outputs "CFWheels is a framework for ColdFusion." --->

#stripTags("<strong>Wheels</strong> is a framework for <a href=""http://www.adobe.com/products/coldfusion"">ColdFusion</a>.")#
Suggest Edits

styleSheetLinkTag()

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

 

Function Syntax

styleSheetLinkTag([ sources, type, media, head, delim ])

Parameters

Parameter
Type
Required
Default
Description

sources

string

No

The name of one or many CSS files in the stylesheets folder, minus the .css extension. (Can also be called with the source argument.) Pass a full URL to generate a tag for an external style sheet.

type

string

No

text/css

The type attribute for the link tag.

media

string

No

all

The media attribute for the link tag.

head

string

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 stylesheets

Examples

<!--- 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(source="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(source="tabs", head=true)#
</body>
Suggest Edits

submitTag()

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.

 
Parameter
Type
Required
Default
Description

value

string

false

Save changes

Message to display in the button form control.

image

string

false

File name of the image file to use in the button form control.

disable

any

false

Whether or not to disable the button upon clicking. (prevents double-clicking.)

prepend

string

false

See documentation for textField

append

string

false

See documentation for textField

<cfoutput>
    #startFormTag(action="something")#
        <!--- form controls go here --->
        #submitTag()#
    #endFormTag()#
</cfoutput>
Suggest Edits

textArea()

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.

 
Parameter
Type
Required
Default
Description

objectName

any

true

See documentation for textField.

property

string

true

See documentation for textField.

association

string

false

See documentation for textfield.

position

string

false

See documentation for textfield.

label

string

false

useDefaultLabel

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

errorElement

string

false

span

See documentation for textField.

errorClass

string

false

fieldWithErrors

See documentation for textField.

<!--- Provide `label` and required `objectName` and `property` --->
<cfoutput>
    #textArea(label="Overview", objectName="article", property="overview")#
</cfoutput>

<!--- 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>
Suggest Edits

textAreaTag()

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.

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

content

string

false

Content to display in textarea on page load.

label

string

false

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

<!--- Basic usage usually involves a `label`, `name`, and `password` --->
<cfoutput>
    #textAreaTag(label="Description", name="description", content=params.description)#
</cfoutput>
Suggest Edits

textField()

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.

 
Parameter
Type
Required
Default
Description

objectName

any

true

The variable name of the object to build the form control for.

property

string

true

The name of the property to use in the form control.

association

string

false

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

false

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

false

useDefaultLabel

The label text to use in the form control.

labelPlacement

string

false

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

false

String to prepend to the form control. Useful to wrap the form control with HTML tags.

append

string

false

String to append to the form control. Useful to wrap the form control with HTML tags.

prependToLabel

string

false

String to prepend to the form control's label. Useful to wrap the form control with HTML tags.

appendToLabel

string

false

String to append to the form control's label. Useful to wrap the form control with HTML tags.

errorElement

string

false

span

HTML tag to wrap the form control with when the object contains errors.

errorClass

string

false

fieldWithErrors

The class name of the HTML tag that wraps the form control when there are errors.

type

string

false

text

Input type attribute. Common examples in HTML5 and later are text (default), email, tel, and url.

labelClass

string

false

String added to the label's class.

<!--- Provide a `label` and the required `objectName` and `property` --->
<cfoutput>
    #textField(label="First Name", objectName="user", property="firstName")#
</cfoutput>

<!--- 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>
Suggest Edits

textFieldTag()

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.

 
Parameter
Type
Required
Default
Description

name

string

true

Name to populate in tag's name attribute.

value

string

false

Value to populate in tag's value attribute.

label

string

false

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

type

string

false

text

See documentation for textField.

<!--- Basic usage usually involves a `label`, `name`, and `value` --->
<cfoutput>
    #textFieldTag(label="Search", name="q", value=params.q)#
</cfoutput>
Suggest Edits

timeAgoInWords()

Pass in a date to this method, and it will return a string describing the approximate time difference between that date and the current date.

 

Function Syntax

timeAgoInWords(fromTime [, includeSeconds, toTime ])

Parameters

Parameter
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.

Examples

<cfset aWhileAgo = Now() - 30>
<cfoutput>#timeAgoInWords(aWhileAgo)#</cfoutput>
Suggest Edits

timeSelect()

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

 
Parameter
Type
Required
Default
Description

objectName

any

false

See documentation for textField.

property

string

false

See documentation for textField.

association

string

false

See documentation for textfield.

position

string

false

See documentation for textfield.

order

string

false

hour,minute,second

Use to change the order of or exclude time select tags.

separator

string

false

:

Use to change the character that is displayed between the time select tags.

minuteStep

numeric

false

1

Pass in 10 to only show minute 10, 20, 30, etc.

secondStep

numeric

false

1

Pass in 10 to only show seconds 10, 20, 30, etc.

includeBlank

any

false

false

See documentation for select.

label

string

false

false

See documentation for dateSelect.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

errorElement

string

false

span

See documentation for textField.

errorClass

string

false

fieldWithErrors

See documentation for textField.

combine

boolean

false

See documentation for dateSelect.

twelveHour

boolean

false

false

whether to display the hours in 24 or 12 hour format. 12 hour format has AM/PM drop downs

<!--- View code --->
<cfoutput>
    #timeSelect(objectName="business", property="openUntil")#
</cfoutput>

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

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

timeSelectTags()

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

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

selected

string

false

See documentation for selectTag.

order

string

false

hour,minute,second

See documentation for timeSelect.

separator

string

false

:

See documentation for timeSelect.

minuteStep

numeric

false

1

See documentation for timeSelect.

secondStep

numeric

false

1

See documentation for timeSelect.

includeBlank

any

false

false

See documentation for select.

label

string

false

See documentation for dateSelect.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

combine

boolean

false

See documentation for dateSelect.

twelveHour

boolean

false

false

See documentation for timeSelect.

<!--- This "Tag" version of function accepts `name` and `selected` instead of binding to a model object --->
<cfoutput>
    ##timeSelectTags(name="timeOfMeeting" selected=params.timeOfMeeting)##
</cfoutput>

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

timeUntilInWords()

Pass in a date to this method, and it will return a string describing the approximate time difference between the current date and that date.

 

Function Syntax

timeUntilInWords(toTime [, includeSeconds, fromTime ])

Parameters

Parameter
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.

Examples

<cfset aLittleAhead = Now() + 30>
<cfoutput>#timeUntilInWords(aLittleAhead)#</cfoutput>
Suggest Edits

titleize()

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

 
Parameter
Type
Required
Default
Description

word

string

true

The text to turn into a title.

#titleize("Wheels is a framework for ColdFusion")#
-> CFWheels Is A Framework For ColdFusion
Suggest Edits

truncate()

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

 
Parameter
Type
Required
Default
Description

text

string

true

The text to truncate.

length

numeric

false

30

Length to truncate the text to.

truncateString

string

false

...

String to replace the last characters with.

#truncate(text="Wheels is a framework for ColdFusion", length=20)#
-> CFWheels is a frame...

#truncate(text="Wheels is a framework for ColdFusion", truncateString=" (more)")#
-> CFWheels is a framework f (more)
Suggest Edits

wordTruncate()

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

 
Parameter
Type
Required
Default
Description

text

string

true

The text to truncate.

length

numeric

false

5

Number of words to truncate the text to.

truncateString

string

false

...

String to replace the last characters with.

#wordTruncate(text="Wheels is a framework for ColdFusion", length=4)#
-> CFWheels is a framework...

#truncate(text="Wheels is a framework for ColdFusion", truncateString=" (more)")#
-> CFWheels is a framework for (more)
Suggest Edits

yearSelectTag()

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

 
Parameter
Type
Required
Default
Description

name

string

true

See documentation for textFieldTag.

selected

string

false

The year that should be selected initially.

startYear

numeric

false

2010

See documentation for dateSelect.

endYear

numeric

false

2020

See documentation for dateSelect.

includeBlank

any

false

false

See documentation for select.

label

string

false

See documentation for textField.

labelPlacement

string

false

around

See documentation for textField.

prepend

string

false

See documentation for textField.

append

string

false

See documentation for textField.

prependToLabel

string

false

See documentation for textField.

appendToLabel

string

false

See documentation for textField.

<!--- View code --->
<cfoutput>
    #yearSelectTag(name="yearOfBirthday", selected=params.yearOfBirthday)#
</cfoutput>

<!--- Only allow selection of year to be for the past 50 years, minimum being 18 years ago --->
<cfset fiftyYearsAgo = Now() - 50>
<cfset eighteenYearsAgo = Now() - 18>
<cfoutput>
	#yearSelectTag(name="yearOfBirthday", selected=params.yearOfBirthday, startYear=fiftyYearsAgo, endYear=eighteenYearsAgo)#
</cfoutput>
Suggest Edits

Controller Initialization Functions

These functions are called from the init() methods of your controller files.

 
Suggest Edits

caches()

Tells CFWheels to cache one or more actions.

 
Parameter
Type
Required
Default
Description

action

string

false

Action(s) to cache. This argument is also aliased as actions.

time

numeric

false

60

Minutes to cache the action(s) for.

static

boolean

false

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

false

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");
Suggest Edits

filterChain()

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

 
Parameter
Type
Required
Default
Description

type

string

false

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");
Suggest Edits

filters()

Tells CFWheels to run a function before an action is run or after an action has been run. You can also specify multiple functions and actions.

 
Parameter
Type
Required
Default
Description

through

string

true

Function(s) to execute before or after the action(s).

type

string

false

before

Whether to run the function(s) before or after the action(s).

only

string

false

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

false

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

false

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");
Suggest Edits

provides()

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.

 
Parameter
Type
Required
Default
Description

formats

string

false

Formats to instruct the controller to provide. Valid values are html (the default), xml, json, csv, pdf, and xls.

provides("html,xml,json");
Suggest Edits

setFilterChain()

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

 
Parameter
Type
Required
Default
Description

chain

array

true

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"}
		]);
Suggest Edits

setVerificationChain()

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

 
Parameter
Type
Required
Default
Description

chain

array

true

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"}
]);
Suggest Edits

usesLayout()

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

 
Parameter
Type
Required
Default
Description

template

string

true

Name of the layout template or function name you want to use.

ajax

string

false

Name of the layout template you want to use for AJAX requests.

except

string

false

List of actions that should not get the layout.

only

string

false

List of actions that should only get the layout.

useDefault

boolean

false

true

When specifying conditions or a function, pass 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");
Suggest Edits

verificationChain()

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);
Suggest Edits

verifies()

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.

 
Parameter
Type
Required
Default
Description

only

string

false

List of action names to limit this verification to.

except

string

false

List of action names to exclude this verification from.

post

any

false

Set to true to verify that this is a POST request.

get

any

false

Set to true to verify that this is a GET request.

ajax

any

false

Set to true to verify that this is an AJAX request.

cookie

string

false

Verify that the passed in variable name exists in the cookie scope.

session

string

false

Verify that the passed in variable name exists in the session scope.

params

string

false

Verify that the passed in variable name exists in the params struct.

handler

string

false

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

false

List of types to check each listed cookie value against (will be passed through to your CFML engine's IsValid function).

sessionTypes

string

false

List of types to check each list session value against (will be passed through to your CFML engine's IsValid function).

paramsTypes

string

false

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");
Suggest Edits

flash()

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

 
Parameter
Type
Required
Default
Description

key

string

false

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();
Suggest Edits

flashClear()

Deletes everything from the Flash.

 
flashClear();
Suggest Edits

flashCount()

Returns how many keys exist in the Flash.

 
count = flashCount();
Suggest Edits

flashDelete()

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

 
Parameter
Type
Required
Default
Description

key

string

true

The key to delete.

flashDelete(key="errorMessage");
Suggest Edits

flashInsert()

Inserts a new key / value into the Flash.

 
flashInsert(msg="It Worked!");
Suggest Edits

flashIsEmpty()

Returns whether or not the Flash is empty.

 
empty = flashIsEmpty();
Suggest Edits

flashKeep()

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

 
Parameter
Type
Required
Default
Description

key

string

false

A key or list of keys to flag for keeping. This argument is also aliased as keys.

// 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");
Suggest Edits

flashKeyExists()

Checks if a specific key exists in the Flash.

 
Parameter
Type
Required
Default
Description

key

string

true

The key to check if it exists.

errorExists = flashKeyExists("error");
Suggest Edits

isAjax()

Returns whether the page was called from JavaScript or not.

 
requestIsAjax = isAjax();
Suggest Edits

isGet()

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

 
requestIsGet = isGet();
Suggest Edits

isPost()

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

 
requestIsPost = isPost();
Suggest Edits

isSecure()

Returns whether CFWheels is communicating over a secure port.

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

onlyProvides()

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 init().

 
Parameter
Type
Required
Default
Description

formats

string

false

See documentation for provides.

action

string

false

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 `init()` function
onlyProvides("html");
Suggest Edits

pagination()

Returns a struct with information about the specificed paginated query. The keys that will be included in the struct are currentPage, totalPages and totalRecords.

 
Parameter
Type
Required
Default
Description

handle

string

false

query

The handle given to the query to return pagination information for.

allAuthors = model("author").findAll(page=1, perPage=25, order="lastName", handle="authorsData");
paginationData = pagination("authorsData");

#pagination().currentPage#
#pagination().totalPages#
#pagination().totalRecords#
Suggest Edits

redirectTo()

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.

 
Parameter
Type
Required
Default
Description

back

boolean

false

false

Set to true to redirect back to the referring page.

addToken

boolean

false

false

See documentation for your CFML engine's implementation of cflocation.

statusCode

numeric

false

302

See documentation for your CFML engine's implementation of cflocation.

route

string

false

Name of a route that you have configured in config/routes.cfm.

controller

string

false

Name of the controller to include in the URL.

action

string

false

Name of the action to include in the URL.

key

any

false

Key(s) to include in the URL.

params

string

false

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 (using URLEncodedFormat() internally). 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

false

Sets an anchor name to be appended to the path.

onlyPath

boolean

false

true

If true, returns only the relative URL (no protocol, host name or port).

host

string

false

Set this to override the current host.

protocol

string

false

Set this to override the current protocol.

port

numeric

false

0

Set this to override the current port number.

url

string

false

Redirect to an external URL.

delay

boolean

false

false

Set to true to delay the redirection until after the rest of your action code has executed.

// 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);
Suggest Edits

renderNothing()

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.

 
// Render a blank white page to the client
renderNothing();
Suggest Edits

renderPage()

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.

 
Parameter
Type
Required
Default
Description

controller

string

false

Controller to include the view page for.

action

string

false

Action to include the view page for.

template

string

false

A specific template to render. Prefix with a leading slash / if you need to build a path from the root views folder.

layout

any

false

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

false

Number of minutes to cache the content for.

returnAs

string

false

Set to string to return the result instead of automatically sending it to the client.

hideDebugInformation

boolean

false

false

Set to true to hide the debug information at the end of the output. This is useful when you're testing XML output in an environment where the global setting for showDebugInformation is true.

// Render a view page for a different action within the same controller
renderPage(action="edit");

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

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

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

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

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

renderPartial()

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

 
Parameter
Type
Required
Default
Description

partial

string

true

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

false

See documentation for renderPage.

layout

string

false

See documentation for renderPage.

returnAs

string

false

See documentation for renderPage.

dataFunction

any

false

true

Name of a controller function to load data from.

// 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");
Suggest Edits

renderText()

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

 
Parameter
Type
Required
Default
Description

text

any

true

The text to be rendered.

// Render just the text "Done!" to the client
renderText("Done!");

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

renderWith()

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.

 
Parameter
Type
Required
Default
Description

data

any

true

Data to format and render.

controller

string

false

See documentation for renderPage.

action

string

false

See documentation for renderPage.

template

string

false

See documentation for renderPage.

layout

any

false

See documentation for renderPage.

cache

any

false

See documentation for renderPage.

returnAs

string

false

See documentation for renderPage.

hideDebugInformation

boolean

false

false

See documentation for renderPage.

// This will provide the formats defined in the `init()` function
products = model("product").findAll();
renderWith(products);
Suggest Edits

response()

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

 
wheelsResponse = response();
Suggest Edits

sendEmail()

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.

 
Parameter
Type
Required
Default
Description

template

string

true

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

true

Email address to send from.

to

string

true

List of email addresses to send the email to.

subject

string

false

The subject line of the email.

layout

any

false

false

Layout(s) to wrap the email template in. This argument is also aliased as layouts.

file

string

false

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

false

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).

		// 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
		);
Suggest Edits

sendFile()

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

 
Parameter
Type
Required
Default
Description

file

string

true

The file to send to the user.

name

string

false

The file name to show in the browser download dialog box.

type

string

false

The HTTP content type to deliver the file as.

disposition

string

false

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

false

Directory outside of the webroot where the file exists. Must be a full path.

deleteFile

boolean

false

false

Pass in true to delete the file on the server after sending it.

// 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");
Suggest Edits

setPagination()

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

 
Parameter
Type
Required
Default
Description

totalRecords

numeric

true

Total count of records that should be represented by the paginated links.

currentPage

numeric

false

1

Page number that should be represented by the data being fetched and the paginated links.

perPage

numeric

false

25

Number of records that should be represented on each page of data.

handle

string

false

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
--->
<cffunction name="myCustomQuery">
	<cfargument name="page" type="numeric">
	<cfargument name="perPage" type="numeric" required="false" default="25">

	<cfquery name="local.customQuery" datasource="##get(''dataSourceName'')##">
		SELECT * FROM users
	</cfquery>

	<cfset setPagination(
    totalRecords=local.customQuery.RecordCount,
    currentPage=arguments.page,
    perPage=arguments.perPage,
    handle="myCustomQueryHandle"
  )>

	<cfreturn customQuery>
</cffunction>

<!--- Controller code --->
<cffunction name="list">
	<cfparam name="params.page" default="1">
	<cfparam name="params.perPage" default="25">

	<cfset 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.
	 --->
	<cfset paginationData = pagination("myCustomQueryHandle")>
</cffunction>

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

#paginationLinks(handle="myCustomQueryHandle")#
</cfoutput>

<!---
  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>

<cfoutput>
#paginationLinks(handle="myCustomQueryHandle")#
</cfoutput>


<!---
	Second method: Handle the pagination through the database
--->

<!---
  Model code
  In your model (ie. `User.cfc`), create a custom method for
  your custom query
--->
<cffunction name="myCustomQuery">
	<cfargument name="page" type="numeric">
	<cfargument name="perPage" type="numeric" required="false" default="25">

	<cfquery
    name="local.customQueryCount"
    datasource="#get('dataSouceName')#"
  >
		SELECT COUNT(*) AS theCount FROM users
	</cfquery>

	<cfquery
    name="local.customQuery"
    datasource="#get('dataSourceName')#"
  >
		SELECT *
    FROM users
		LIMIT #arguments.page#
    OFFSET #arguments.perPage#
	</cfquery>

	<!---
    Notice the we use the value from the first query for
    `totalRecords`
  --->
	<cfset setPagination(
    totalRecords=local.customQueryCount.theCount,
    currentPage=arguments.page,
    perPage=arguments.perPage,
    handle="myCustomQueryHandle"
  )>

	<!--- We return the second query --->
	<cfreturn customQuery>
</cffunction>

<!--- Controller code --->
<cffunction name="list">
	<cfparam name="params.page" default="1">
	<cfparam name="params.perPage" default="25">

  <cfset allUsers = model("user").myCustomQuery(
    page=params.page,
    perPage=params.perPage
  )>
</cffunction>

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

#paginationLinks(handle="myCustomQueryHandle")#
</cfoutput>

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

<cfoutput>
#paginationLinks(handle="myCustomQueryHandle")#
</cfoutput>
Suggest Edits

setResponse()

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

 
Parameter
Type
Required
Default
Description

content

string

true

The content to set as the response.

setResponse(newReponse);
Suggest Edits

Global Helper Functions

These functions are general purpose functions and can be called from anywhere.

 
Suggest Edits

controller()

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

 

Function Syntax

controller(name [, params ])

Parameters

Parameter
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).

Examples

<cfset testController = controller("users", params)>
Suggest Edits

deobfuscateParam()

Deobfuscates a value.

 

Function Syntax

deobfuscateParam(param)

Parameters

Parameter
Type
Required
Default
Description

param

string

Yes

Value to deobfuscate.

Examples

<!--- Get the original value from an obfuscated one --->
<cfset originalValue = deobfuscateParam("b7ab9a50")>
Suggest Edits

get()

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

 

Function Syntax

get(name [, functionName ])

Parameters

Parameter
Type
Required
Default
Description

name

string

Yes

Variable name to get setting for.

functionName

string

No

Function name to get setting for.

Examples

<!--- Get the current value for the `tableNamePrefix` Wheels setting --->
<cfset setting = get("tableNamePrefix")>

<!--- Get the default for the `message` argument of the `validatesConfirmationOf` method  --->
<cfset setting = get(functionName="validatesConfirmationOf", name="message")>
Suggest Edits

mimeTypes()

Returns an associated MIME type based on a file extension.

 

Function Syntax

mimeTypes(extension [, fallback ])

Parameters

Parameter
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.

Examples

<!--- Get the internally-stored MIME type for `xls` --->
<cfset 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 --->
<cfset mimeType = mimeTypes(extension=params.type, fallback="text/plain")>
Suggest Edits

model()

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

 

Function Syntax

model(name)

Parameters

Parameter
Type
Required
Default
Description

name

string

Yes

Name of the model to get a reference to.

Examples

<!--- 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 --->
<cfset authorObject = model("author").findByKey(1)>
Suggest Edits

obfuscateParam()

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

 

Function Syntax

obfuscateParam(param)

Parameters

Parameter
Type
Required
Default
Description

param

any

Yes

Value to obfuscate.

Examples

<!--- Obfuscate the primary key value `99` --->
<cfset newValue = obfuscateParam(99)>
Suggest Edits

pluginNames()

Returns a list of all installed plugins' names.

 

Function Syntax

pluginNames()

Parameters

None.

Examples

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

urlFor()

Creates an internal URL based on supplied arguments.

 

Function Syntax

urlFor([ route, controller, action, key, params, anchor, onlyPath, host, protocol, port ])

Parameters

Parameter
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 (using URLEncodedFormat() internally). 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.

Examples

<!--- 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")#
Suggest Edits

capitalize()

Returns the text with the first character converted to uppercase.

 

Function Syntax

capitalize(text)

Parameters

Parameter
Type
Required
Default
Description

text

string

Yes

Text to capitalize.

Examples

<!--- Capitalize a sentence, will result in "Wheels is a framework" --->
#capitalize("wheels is a framework")#
Suggest Edits

humanize()

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

 

Function Syntax

humanize(text [, except ])

Parameters

Parameter
Type
Required
Default
Description

text

string

Yes

Text to humanize.

except

string

No

a list of strings (space separated) to replace within the output.

Examples

<!--- 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")#
Suggest Edits

hyphenize()

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

 

Function Syntax

hyphenize(string)

Parameters

Parameter
Type
Required
Default
Description

string

string

Yes

The string to hyphenize.

Examples

<!--- Outputs "my-blog-post" --->
<cfoutput>
    #hyphenize("myBlogPost")#
</cfoutput>
Suggest Edits

pluralize()

Returns the plural form of the passed in word. Can also pluralize a word based on a value passed to the count argument.

 

Function Syntax

pluralize(word [, count, returnCount ])

Parameters

Parameter
Type
Required
Default
Description

word

string

Yes

The word to pluralize.

count

numeric

No

Pluralization will occur when this value is not 1.

returnCount

boolean

No

Will return count prepended to the pluralization when true and count is not -1.

Examples

<!--- 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)#
Suggest Edits

singularize()

Returns the singular form of the passed in word.

 

Function Syntax

singularize(word)

Parameters

Parameter
Type
Required
Default
Description

word

string

Yes

String to singularize.

Examples

<!--- Singularize a word, will result in "language" --->
#singularize("languages")#
Suggest Edits

toXHTML()

Returns an XHTML-compliant string.

 

Function Syntax

toXHTML(text)

Parameters

Parameter
Type
Required
Default
Description

text

string

Yes

String to make XHTML-compliant.

Examples

<!--- Outputs `productId=5&amp;categoryId=12&amp;returningCustomer=1` --->
<cfoutput>
    #toXHTML("productId=5&categoryId=12&returningCustomer=1")#
</cfoutput>
Suggest Edits

Configuration Functions

These functions should be called from files in the config folder.

 
Suggest Edits

addDefaultRoutes()

Adds the default CFWheels routes (for example, [controller]/[action]/[key], etc.) to your application. Only use this method if you have set loadDefaultRoutes to false and want to control exactly where in the route order you want to place the default routes.

 
<!--- Adds the default routes to your application (done in `config/routes.cfm`) --->
<cfset addDefaultRoutes()>
Suggest Edits

addFormat()

Adds a new MIME format to your Wheels application for use with responding to multiple formats.

 
Parameter
Type
Required
Default
Description

extension

string

true

File extension to add.

mimeType

string

true

Matching MIME type to associate with the file extension.

<!--- Add the `js` format --->
<cfset addFormat(extension="js", mimeType="text/javascript")>

<!--- Add the `ppt` and `pptx` formats --->
<cfset addFormat(extension="ppt", mimeType="application/vnd.ms-powerpoint")>
<cfset addFormat(extension="pptx", mimeType="application/vnd.ms-powerpoint")>
Suggest Edits

addRoute()

Adds a new route to your application.

 
Parameter
Type
Required
Default
Description

name

string

false

Name for the route. This is referenced as the name argument in functions based on URLFor() like linkTo(), startFormTag(), etc.

pattern

string

true

The URL pattern that the route will match.

controller

string

false

Controller to call when route matches (unless the controller name exists in the pattern).

action

string

false

Action to call when route matches (unless the action name exists in the pattern).

<!--- Example 1: Adds a route which will invoke the `profile` action on the `user` controller with `params.userName` set when the URL matches the `pattern` argument --->
<cfset addRoute(name="userProfile", pattern="user/[username]", controller="user", action="profile")>

<!--- Example 2: Category/product URLs. Note the order of precedence is such that the more specific route should be defined first so Wheels will fall back to the less-specific version if it's not found --->
<cfset addRoute(name="product", pattern="products/[categorySlug]/[productSlug]", controller="products", action="product")>
<cfset addRoute(name="productCategory", pattern="products/[categorySlug]", controller="products", action="category")>
<cfset addRoute(name="products", pattern="products", controller="products", action="index")>

<!--- Example 3: Change the `home` route. This should be listed last because it is least specific --->
<cfset addRoute(name="home", pattern="", controller="main", action="index")>
Suggest Edits

set()

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

 
<!--- Example 1: Set the `URLRewriting` setting to `Partial` --->
<cfset 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. --->
<cfset 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 --->
<cfset set(functionName="textField", labelPlacement="before", prependToLabel="<div>", append="</div>", appendToLabel="<br />")>
Suggest Edits

A-Z Functions

 

A

B

C

D

E

F

G

H

I

J

K

L

M

N

O

P

R

S

T

U

V

W

Y