I see that stockroom is a reference field, which means it's referencing another table (likely cmn_location or a custom table related to stockrooms). The location field also needs to be compatible with the reference type you're trying to set.
Given that both stockroom and location presumably reference the same table or have compatible reference types, the script should copy the reference value correctly without clearing the field.
To ensure the location field value is properly set, the script must handle the reference value correctly. Below is an updated script that checks and copies the reference value from stockroom to location.
Updated Background Script:
(function() {
// Define the GlideRecord object for the alm_hardware table
var hardwareGR = new GlideRecord('alm_hardware');
// Add a query to process records with a non-null stockroom field
hardwareGR.addNotNullQuery('stockroom');
// Query all records in the alm_hardware table that satisfy the condition
hardwareGR.query();
// Iterate through each record
while (hardwareGR.next()) {
// Get the reference value from the stockroom field
var stockroomSysId = hardwareGR.getValue('stockroom');
if (stockroomSysId) {
// Set the location field to the same reference value as stockroom
hardwareGR.setValue('location', stockroomSysId);
// Update the record in the database
hardwareGR.update();
} else {
gs.log('Record with sys_id ' + hardwareGR.sys_id + ' has no stockroom value.');
}
}
// Optional: Log a completion message
gs.log('Copied stockroom field values to location field for alm_hardware records.');
})();
Steps to Execute:
- Copy the script provided above.
- Paste it into the 'Run script' area in the
Scripts - Background module.
- Click the
Run Script button to execute the script.
Important Notes:
-
Testing:
Always test the script in a sub-production instance (like Development or Test) before running it in a production environment to ensure it performs as expected.
-
Backup:
Consider taking a backup or snapshot of the affected records (or the entire table) before performing bulk updates.
-
Field Type Compatibility:
Ensure that the location field is of the same type and references the same table as the stockroom field. If not, you might need to make adjustments to handle the correct reference type mapping.
-
Debugging:
You may add additional gs.log() statements for better monitoring and debugging during the execution phase. For example:
gs.log('Updating record with sys_id: ' + hardwareGR.sys_id + ', setting location to: ' + stockroomSysId);
This script ensures that the stockroom reference value is copied to the location reference field correctly, preventing the location field from being cleared unintentionally. Make sure to have the appropriate permissions to execute background scripts in your instance.