Back
beforeSave()
Registers method(s) that should be called before an object is saved. This is useful for performing transformations, validations, or logging before data is persisted.
1. Basic usage: run a method before save
function config() {
beforeSave("fixObj");
}
function fixObj() {
// Example: Trim whitespace before saving
this.username = trim(this.username);
}
2. Automatically update a timestamp
function config() {
beforeSave("updateTimestamp");
}
function updateTimestamp() {
this.lastModifiedAt = now();
}
3. Normalize data before saving
function config() {
beforeSave("normalizeData");
}
function normalizeData() {
// Example: ensure email is lowercase
this.email = lcase(this.email);
// Example: capitalize first name
this.firstName = ucase(left(this.firstName, 1)) & mid(this.firstName, 2);
}
4. Prevent save if conditions fail
function config() {
beforeSave("blockInactiveUsers");
}
function blockInactiveUsers() {
if (!this.isActive) {
throw(type="ValidationException", message="Inactive users cannot be saved.");
}
}
Copied!