CFWheels taking action on a particular error
http://cfwheels.org/docs/1-1/function/errorson
If you have more than one error on a property (aka column in a database table, as defined in your model) you need to create custom errors so you can name them
For instance, in your User.cfc model in your custom error method you have:
this.addError(property="email", name="uniqueEmail", message="That e-mail address is already in use.");
(You call this error handler with validate() and the name of the function, see http://cfwheels.org/docs/1-1/function/validate)
The key part for us here is the name.
This allows you to use errorsOn like this, in your Users.cfc controller:
var emailExistsError = user.errorsOn(property="email", name="uniqueEmail");
if (!ArrayIsEmpty(emailExistsError)) {
// Take action on this error...
// In this case we were doing a writeLog() and a redirectTo().
}
The User.cfc code in context, with most unrelated code removed:
<cfcomponent extends="Model" output="false">
<cfscript>
public function init() {
hasOne(name="UserProfile", dependent="delete");
hasMany("Venues");
automaticValidations(false);
validatesFormatOf(property="email", type="email", message="The e-mail address is not valid.");
validatesConfirmationOf(property="password",message="Passwords do not match.");
validate(methods="uniqueEmail");
} //end init()
// Check before updating a user record that e-mail is unique (if editing a user, ignore current user).
// We are not using validatesUniquenessOf(property="email", ...) because built-in validators cannot name their errors.
function uniqueEmail() {
// Only add an ID if we're editing a user.
if (structKeyExists(this, "id")) {
var idConditon = " AND id <> #this.id#";
}
else {
var idCondition = "";
}
uniquee = model("user").findOne(where="email = '#this.email#'" & idCondition);
if (isObject(uniquee)) {
// In Users.cfc we'll use this named error to, if not editing a user, redirect to log in.
this.addError(property="email", name="uniqueEmail", message="That e-mail address is already in use.");
}
}
</cfscript>
</cfcomponent>
Comments
Post new comment