In some instances, we use identifiers other than the internal or external IDs of the records. This could be a concatenation of multiple fields, or auto-generated number from another system that is integrated with the current.
The script below will run a search that finds the value of the field and returns an error when it detects a duplicate.
/**
* @NApiVersion 2.1
* @NScriptType UserEventScript
*/
define(['N/search','N/error'],
(search,error) => {
/**
* 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) => {
var thisRecord = scriptContext.newRecord;
var identifier = thisRecord.getValue({
fieldId: 'custrecord_identifier'
});
var thisRecInternalId = scriptContext.newRecord.id;
var column = [], internalid = [], index = [], intId = 0;
column[0] = search.createColumn({name: "internalid", label: "Internal ID"})
//create a search to look for the same discussion ID
var searchObject = search.create({
type: "customrecord108",
filters:
[
["custrecord_identifier","is",identifier]
],
columns: column
});
var searchResultCount = searchObject.runPaged().count;
var searchResultSet = searchObject.run()
//if a match is found, index will increase by one.
searchResultSet.each(function(result){
internalid[index] = result.getValue(column[0]);
if (index == 0){
intId = internalid[index];
}
index++;
return true;
});
var error_duplicateDiscussion = error.create({
name: 'DUPLICATE_DISCUSSION',
message: "Discussion ID " + identifier + " already exists.",
notifyOff: true
});
if(searchResultCount == 0){
return true;
} else if (scriptContext.type == scriptContext.UserEventType.CREATE && searchResultCount != 0){//New record and ID already exists
throw error_duplicateDiscussion;
} else if (scriptContext.type == scriptContext.UserEventType.EDIT && searchResultCount == 1 && intId != thisRecInternalId){ //Editing an existing record’s ID and the ID already exists in another record
throw error_duplicateDiscussion;
} else if(searchResultCount > 1){
throw error_duplicateDiscussion;
} else {
return true;
}
}
return {beforeSubmit}
});