The following user event script throws error for Unique value fields if duplicate values is entered.
The script will throw error for record create/edit in UI and also via SOAP API.
The fields are :BBCPRODUCTID_AU,BBCPRODUCTID_MY
/**
* @NApiVersion 2.1
* @NScriptType UserEventScript
*/
define(["N/record", "N/search", "N/error"],
(record, search, error) => {
/**
* @description search to find if the value in the field already exist
* @param {fieldId} fieldId of the item to be searched
* @param {value} current value in the field
*/
function itemFieldValueSearch(fieldId, value) {
try {
let itemSearchObj = search.create({
type: "item",
filters:
[fieldId, "is", value]
,
columns:
[
search.createColumn({ name: "internalid", label: "Internal ID" })
]
});
let searchResultCount = itemSearchObj.runPaged().count;
return searchResultCount;
} catch (e) {
log.error("error @ itemFieldValueSearch ", e);
}
}
/**
* Defines the function definition that is executed before record is submitted.
* @param {Object} scriptContext
* @param {Record} scriptContext.newRecord - New record
* @param {Record} scriptContext.oldRecord - Old record
* @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum
* @since 2015.2
*/
const beforeSubmit = (scriptContext) => {
// Validation on Create context
if (scriptContext.type == 'create') {
let errMsgFields = [];
try {
let newRec = scriptContext.newRecord;
// Validation check for field : BBCPRODUCTID_AU
let productIdAU = newRec.getValue({ fieldId: 'custitemcustitem_jj_bggn_1081' });
if (productIdAU) {
countAU = itemFieldValueSearch("custitemcustitem_jj_bggn_1081", productIdAU);
if (countAU > 0) {
errMsgFields.push("BBCPRODUCTID_AU");
}
}
// Validation check for field : BBCPRODUCTID_MY
let productIdMY = newRec.getValue({ fieldId: 'custitem_jj_bggn_1082' });
if (productIdMY) {
countAU = itemFieldValueSearch("custitem_jj_bggn_1082", productIdMY);
if (countAU > 0) {
errMsgFields.push("BBCPRODUCTID_MY");
}
}
// if validation fails throw error message
if (errMsgFields.length > 0) {
// create error msg string
errorMsg = errMsgFields.join(", ");
let msgString = (errMsgFields.length == 1) ? `Uniqueness error for Field: ${errorMsg}` : `Uniqueness error for Fields: ${errorMsg}`;
throw msgString;
}
}
}
return { beforeSubmit }
});