在提交验证记录之前将其提交到数据库之前
对于此示例,我们希望确保标记为项目资源的任何员工也定义了适当的人工成本。
// 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 beforeSubmit(type) {
if (!isEmployeeValid(nlapiGetNewRecord())) {
throw nlapiCreateError("STOIC_ERR_INVALID_DATA", "Employee data is not valid", true);
}
}
function isEmployeeValid(employee) {
return (!isProjectResource(employee) || hasValidLaborCost(employee));
}
function isProjectResource(employee) {
return (employee.getFieldValue("isjobresource") === "T");
}
function hasValidLaborCost(employee) {
var laborCost = parseFloat(employee.getFieldValue("laborcost"));
return (Boolean(laborCost) && (laborCost > 0));
}
exports.beforeSubmit = beforeSubmit;
return exports;
})();
// 2.0
define(["N/error"], function (err) {
var exports = {};
/**
* User Event 2.0 example detailing usage of the Submit events
*
* @NApiVersion 2.x
* @NModuleScope SameAccount
* @NScriptType UserEventScript
* @appliedtorecord employee
*/
function beforeSubmit(scriptContext) {
if (!isEmployeeValid(scriptContext)) {
throw err.create({
"name": "STOIC_ERR_INVALID_DATA",
"message": "Employee data is not valid",
"notifyOff": true
});
}
}
function isEmployeeValid(scriptContext) {
return (!isProjectResource(scriptContext.newRecord) || hasValidLaborCost(scriptContext.newRecord));
}
function isProjectResource(employee) {
return (employee.getValue({"fieldId" : "isjobresource"}));
}
function hasValidLaborCost(employee) {
var laborCost = employee.getValue({"fieldId" : "laborcost"});
return (Boolean(laborCost) && (laborCost > 0));
}
exports.beforeSubmit = beforeSubmit;
return exports;
});
请注意,我们将对新记录的引用传递给我们的验证,因为我们不关心过去的值是什么; 我们只关心即将写入数据库的值。在 2.0 中,我们通过 scriptContext.newRecord
引用来实现,在 1.0 中我们调用全局函数 nlapiGetNewRecord
。
当提交的数据无效时,我们会创建并抛出错误。在 beforeSubmit
事件中,为了防止将更改写入数据库,你的函数必须知道异常。通常开发人员试图从他们的功能中获取,希望这足够了,但这还不够。使用 N/error
模块在 2.0 中创建错误对象,在 1.0 中使用全局 nlapiCreateError
函数创建错误对象; 然后,我们使用我们创建的错误对象和 throw
关键字来引发异常。