Entering a value in a field when the Update Button is pressed using a business rule

wkhong
Tera Contributor

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.

 

 

1 ACCEPTED SOLUTION

@wkhong 

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.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

9 REPLIES 9

Ankur Bawiskar
Tera Patron
Tera Patron

@wkhong 

can you share your script here instead of screenshot?

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

 

 

Here. Thank you.

스크린샷 2024-12-30 161146.png

@wkhong 

share the actual script and not the image please

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@wkhong 

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.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader