Skip to content

Commit 072e481

Browse files
authored
Create script.js
1 parent abbe375 commit 072e481

File tree

1 file changed

+46
-0
lines changed
  • Server-Side Components/Background Scripts/Copy Field Values and Insert in Target Record

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
/**
2+
* Copies specified fields from a source record to a newly created target record,
3+
* validating all fields before performing the insert operation.
4+
*
5+
* @param {string} sourceTable - The name of the source table.
6+
* @param {string} sourceId - The sys_id of the source record.
7+
* @param {string} targetTable - The name of the target table.
8+
* @param {string[]} fields - An array of field names to copy.
9+
* @returns {string|null} The sys_id of the newly created target record, or null on failure.
10+
*/
11+
function copyFieldsValidated(sourceTable, sourceId, targetTable, fields) {
12+
var src = new GlideRecord(sourceTable);
13+
if (!src.get(sourceId)) {
14+
gs.error("Source record not found in " + sourceTable + " with sys_id: " + sourceId);
15+
return null;
16+
}
17+
18+
var tgt = new GlideRecord(targetTable);
19+
tgt.initialize();
20+
var allFieldsAreValid = true;
21+
// First, validate all fields before doing any work
22+
fields.forEach(function(f) {
23+
if (!src.isValidField(f) || !tgt.isValidField(f)) {
24+
gs.warn("Field [" + f + "] is not valid in both " + sourceTable + " and " + targetTable + ". Aborting insert.");
25+
allFieldsAreValid = false;
26+
}
27+
});
28+
29+
// Proceed with copying and inserting only if all fields are valid
30+
if (allFieldsAreValid) {
31+
fields.forEach(function(f) {
32+
tgt.setValue(f, src.getValue(f));
33+
});
34+
var newId = tgt.insert();
35+
if (newId) {
36+
gs.info("Record copied from " + sourceTable + " → " + targetTable + ". New sys_id: " + newId);
37+
return newId;
38+
} else {
39+
gs.error("Failed to insert new record into " + targetTable);
40+
return null;
41+
}
42+
} else {
43+
gs.error("Aborting record insert due to invalid fields.");
44+
return null;
45+
}
46+
}

0 commit comments

Comments
 (0)