- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-29-2024 11:12 PM
Hello,
I created a Business Rule to populate a field with a value when the Update button is clicked. I wrote the script as follows, checked Before and Update to trigger the Business Rule, but it’s not working.
Is there an issue with the script itself? Or is the problem related to checking only Before and Update? I would like to understand what’s causing this issue.
Solved! Go to Solution.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-29-2024 11:32 PM
try this script once along with script include and it will work
Ensure the BR is before update.
Script Include:
var UniqueCodeGenerator = Class.create();
UniqueCodeGenerator.prototype = {
initialize: function() {},
generateUniqueCode: function(currentSysId) {
var attempts = 0;
var maxAttempts = 100;
var uniqueCode = '';
var isUnique = false;
while (attempts < maxAttempts && !isUnique) {
uniqueCode = this._generateRandomCode();
isUnique = this._checkUniqueness(uniqueCode, currentSysId);
attempts++;
}
if (!isUnique) {
gs.log('Failed to generate a unique code in ' + maxAttempts + ' attempts');
}
return uniqueCode;
},
_generateRandomCode: function() {
// Generate a random code (e.g., 8-character alphanumeric)
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var code = '';
for (var i = 0; i < 8; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
return code;
},
_checkUniqueness: function(code, currentSysId) {
// Check if the code is unique (e.g., by querying a table)
var gr = new GlideRecord('sys_user');
gr.addQuery('u_unique_code', code);
gr.addQuery('sys_id', '!=', currentSysId)
gr.query();
return !gr.hasNext();
},
type: 'UniqueCodeGenerator'
};
Business rule script
(function executeRule(current, previous /*null when async*/) {
// Add your code here
var generator = new UniqueCodeGenerator();
var uniqueCode = generator.generateUniqueCode(current.getUniqueValue());
current.u_unique_code = uniqueCode;
})(current, previous);
If my response helped please mark it correct and close the thread so that it benefits future readers.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-30-2024 12:35 AM
Thank you very much for the great response. I have written this code exactly as provided in the Script Include and Business Rule. However, the System Log shows the following message:
"Invalid query detected, please check logs for details [Unknown field unique_code in table sys_user]"
I have already confirmed that the field exists, yet I still cannot understand why the Business Rule is not being executed.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-30-2024 12:45 AM
are you sure the field name u_unique_code is correct?
Otherwise the script I shared will work fine.
If my response helped please mark it correct and close the thread so that it benefits future readers.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-29-2024 11:24 PM
Can you at copy paste the below script and check the logs of what all you can see in the system logs table -
(function executeRule(current, previous /*null when async*/) {
gs.log('Before Insert Business Rule triggered for table: ' + current.getTableName());
const generateUniqueCode = () => {
return Array.from({ length: 2 }, () => "ABCDEFGHIJKLMNOPQRSTUVWXYZ".charAt(Math.random() * 26 | 0)).join('') +
Array.from({ length: 8 }, () => Math.random() * 10 | 0).join('');
};
if (!current.u_unique_code) {
gs.log('u_unique_code is empty. Generating a new unique code.');
const gr = new GlideRecord('sys_user');
let uniqueCode, attempts = 0;
do {
gs.log('Attempt number: ' + (attempts + 1));
if (++attempts > 100) {
gs.addErrorMessage('Unable to generate a unique code. Please contact the administrator.');
current.setAbortAction(true);
gs.log('Error: Maximum attempts exceeded while generating unique code.');
return;
}
uniqueCode = generateUniqueCode();
gs.log('Generated unique code: ' + uniqueCode);
gr.initialize();
gr.addQuery('u_unique_code', uniqueCode);
gr.addQuery('sys_id', '!=', current.sys_id);
gr.query();
} while (gr.hasNext());
current.u_unique_code = uniqueCode;
gs.log('Assigned unique code: ' + uniqueCode);
} else {
gs.log('u_unique_code already exists: ' + current.u_unique_code);
}
gs.log('Before Insert Business Rule execution completed.');
})(current, previous);
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-29-2024 11:55 PM
Invalid query detected, please check logs for details [Unknown field unique_code in table sys_user]
I found this message in System log. but i have already made this Unique Code field.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
12-30-2024 12:55 AM
The error occurs when the system cannot find the specified field in the object. To resolve this, try right-clicking the field and selecting "Configure Dictionary" to verify or update the field's configuration.
also, try this once -
(function executeRule(current, previous) {
gs.log('Before Insert Business Rule triggered for table: ' + current.getTableName());
const userRecord = new GlideRecord('sys_user'); // Declaring the GlideRecord object with const
userRecord.addQuery('u_unique_code', '12345');
userRecord.query();
if (userRecord.next()) {
gs.log('User found with unique code 12345');
}
})(current, previous);