提交后确定字段是否已更改

在将记录存储在数据库中之后,我们想要检查记录上的更改内容。我们将通过比较旧记录实例和新记录实例之间的值来进行此检查。

// 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 和一个空字符串的情况。