How to prevent duplicate chg_template records being created in the 'template' part

matthew_hughes
Kilo Sage

In ServiceNow, I'm trying to prevent duplicate change templates being created within the change request template part so the following can't exist simultaneously:

matthew_hughes_0-1795077310227.png

 

matthew_hughes_2-1795077369659.png

 

I'm trying to prevent this with the below business rule:

matthew_hughes_3-1795077435433.png

 

I'm using the below script in the Advanced Section:

(function executeRule(current, previous /* null when async */) {

    function normaliseTemplate(template) {

        if (!template) {
            return '';
        }

        var parts = template.toString().split('^');
        var values = [];

        for (var i = 0; i < parts.length; i++) {

            if (parts[i] && parts[i] != 'EQ') {
                values.push(parts[i]);
            }
        }

        values.sort();

        return values.join('^');
    }

    var currentTemplate = normaliseTemplate(
        current.getValue('template')
    );

    if (!currentTemplate) {
        return;
    }

    var templateGR = new GlideRecord('chg_template');

    templateGR.addQuery(
        'sys_id',
        '!=',
        current.getUniqueValue()
    );

    templateGR.query();

    while (templateGR.next()) {

        var existingTemplate = normaliseTemplate(
            templateGR.getValue('template')
        );

        if (currentTemplate == existingTemplate) {

            gs.addErrorMessage(
                'A Change Template already exists with the same template content.'
            );

            current.setAbortAction(true);
            return;
        }
    }

})(current, previous);

 

However, it's not stopping the duplication. I was just wondering if anyone has seen this before or knows how to prevent duplication?

 

0 REPLIES 0