提交後確定欄位是否已更改
在將記錄儲存在資料庫中之後,我們想要檢查記錄上的更改內容。我們將通過比較舊記錄例項和新記錄例項之間的值來進行此檢查。
// 1.0, Revealing Module pattern
var myNamespace = myNamespace || {};
myNamespace.example = (function () {
/**
* User Event 1.0 example detailing usage of the Submit events
*
* @appliedtorecord employee
*/
var exports = {};
function afterSubmit(type) {
notifySupervisor();
}
function notifySupervisor() {
// Old and New record instances are retrieved from global functions
var employee = nlapiGetNewRecord();
var prevEmployee = nlapiGetOldRecord();
// If Employee Status didn't change, there's nothing to do
if (!didStatusChange(employee, prevEmployee)) {
return;
}
// Otherwise, continue with business logic...
}
function didStatusChange(employee, prevEmployee) {
var status = employee.getFieldValue("employeestatus");
var prevStatus = prevEmployee.getFieldValue("employeestatus");
/* !! Caution !!
* Empty fields from the Old record come back as `null`
* Empty fields from the New record come back as an empty String
* This means you cannot simply compare the old and new
*/
return ((prevStatus || status) && (status !== prevStatus));
}
exports.afterSubmit = afterSubmit;
return exports;
})();
// 2.0
define(["N/runtime"], function (runtime) {
/**
* User Event 2.0 example detailing usage of the Submit events
*
* @NApiVersion 2.x
* @NModuleScope SameAccount
* @NScriptType UserEventScript
* @appliedtorecord employee
*/
var exports = {};
function afterSubmit(scriptContext) {
notifySupervisor(scriptContext);
}
function notifySupervisor(scriptContext) {
// Old and New records are simply properties on scriptContext
var employee = scriptContext.newRecord;
var prevEmployee = scriptContext.oldRecord;
// If Employee Status didn't change, there's nothing to do
if (!didStatusChange(employee, prevEmployee)) {
return;
}
// Otherwise, continue with business logic...
}
function didStatusChange(employee, prevEmployee) {
var status = employee.getValue({"fieldId" : "employeestatus"});
var prevStatus = prevEmployee.getValue({"fieldId" : "employeestatus"});
/* !! Caution !!
* Empty fields from the Old record come back as `null`
* Empty fields from the New record come back as an empty String
* This means you cannot simply compare the old and new
*/
return ((prevStatus || status) && (status !== prevStatus));
}
exports.afterSubmit = afterSubmit;
return exports;
});
在比較舊記錄和新記錄之間的值時要非常謹慎。從空場舊紀錄是返回 null
,而從空領域的新記錄中為空字串返回。這意味著你不能簡單地比較舊的和新的,否則你會得到誤報。你編寫的任何邏輯都必須處理一個 null
和一個空字串的情況。