onSubmit script error: TypeError: When I am edited ans submitted the variable set in Finance case

Sivakrishna
Kilo Sage

Hi,

      I have a Create New Contractor Record Producer, when I am submitted the record producer, it will create a finance case. I have open the Finance case in Native UI and in this finance case a variable set is there, when I have edited and submitted the variable set variables in finance case, it showing me the below error:

                     onSubmit script error: TypeError: Cannot read properties of undefined (reading 'element'):

 

I am unable to resolve this error and error screenshot and onSubmit catalog client script code is enclosed for quick reference. The issue is in onSubmit client script:

 

function onSubmit() {
//Type appropriate comment here, and begin script below
// Basic formatting for Iban numbers <length>!<type> | Types are a=[A-Z], n=[0-9], c=[0-9A-Z];
// Example: "BH2!n4!a14!c"

var pass = true;

var spThis = this;

// Service Portal Section
if (spThis) {

var catItem = spThis.angular.element(spThis.$('#sc_cat_item').find('sp-variable-layout')[0]).scope();
var parent_g_form = catItem.getGlideForm();
parent_g_form.setValue('u_attach_reference_banking_documents', 'Yes');

}
this.IBAN_FMT = /((\d+)!([acn])|[^\d]+)/gi;
this.IBAN_N = "[0-9]";
this.IBAN_A = "[A-Z]";
this.IBAN_C = "[0-9A-Z]";


//console.log('PB Debug - top.scratchpad.bank_data is ' + JSON.stringify(top.scratchpad.bank_data));

if (top.scratchpad == undefined) {
return true;
}

var structNum = top.scratchpad.bank_data.bank_key + ''; //Modified as part of DFCT0014370
var fieldSC = g_form.getValue('u_bank_key_sort_code');

g_form.hideFieldMsg('u_bank_key_sort_code');

if (!checkStruct(fieldSC, structNum)) {
g_form.showFieldMsg('u_bank_key_sort_code', 'Invalid Bank Key format for the country: ' + structNum, 'error');
pass = false;
}

var structAcc = top.scratchpad.bank_data.bank_account + '';
var fieldAc = g_form.getValue('u_bank_account');
g_form.hideFieldMsg('u_bank_account');

var checkAcc = checkStruct(fieldAc, structAcc);
//console.log("PB Debug - checkStruct on bank Acc returned " + checkAcc);
if (!checkStruct(fieldAc, structAcc)) {
//console.log('PB Debug - bank_account validation returned an error');
g_form.showFieldMsg('u_bank_account', 'Invalid Bank Account format for the country: ' + structAcc, 'error');
pass = false;
}

var structBCK = top.scratchpad.bank_data.bank_control_key + '';
var fieldBCK = g_form.getValue('u_bank_control_key_if_applicable');
if (structBCK != undefined && structBCK != '') {

g_form.hideFieldMsg('u_bank_control_key_if_applicable');

if (!checkStruct(fieldBCK, structBCK)) {
g_form.showFieldMsg('u_bank_control_key_if_applicable', 'Invalid Bank Control Key format for the country: ' + structBCK, 'error');
pass = false;
}
}

var structIB = top.scratchpad.bank_data.iban_structure + '';
var fieldIB = g_form.getValue('u_iban_code');
g_form.hideFieldMsg('u_iban_code');

if (structIB != '') {
if (!checkStruct(fieldIB, structIB)) {
g_form.showFieldMsg('u_iban_code', 'Invalid IBAN format for the country: ' + structIB, 'error');
pass = false;
}

if (!isIBAN(fieldIB)) {
g_form.showFieldMsg('u_iban_code', 'Invalid IBAN Value', 'error');
pass = false;
}
}

var ISO = top.scratchpad.bank_data.country_iso2 + '';
var rule = "^[A-Z0-9]{4}" + ISO + "[A-Z0-9]{2}(?:|[A-Z0-9]{3})$";
var fieldSwift = g_form.getValue('u_swift_bic_code');
var reg = new RegExp(rule, '');

g_form.hideFieldMsg('u_swift_bic_code');

if (!reg.test(fieldSwift) && fieldSwift!= '') {
g_form.showFieldMsg('u_swift_bic_code', 'Invalid Swift BIC code format for the country: ' + rule, 'error');
pass = false;
}

return pass;

// Function: convertIbanToRegEx(iBan)
//  IN: Format string (in iBan format)
// OUT: Regex string to test bank numbers
function convertStructToRegEx(iBan) {
// Constants
var formatLen = 0,
formatType = 1; // Indexes of format variables

var regEx = '^'; // Force match to start at the beginning of the string
var matches = iBan.match(this.IBAN_FMT);

// Process the fields defined
//alert('iban ' + iBan + 'length' + matches.length);
if(matches.length > 1 && iBan.indexOf('to') > 0){
if (matches[0].indexOf('!') >= 0 && matches[2].indexOf('!') >= 0) {
// It's a format
var formRange1 = matches[0].split('!');
var formRange2 = matches[2].split('!');
switch (formRange1[formatType]){
case 'a': // Alpha only
regEx += this.IBAN_A + '{' + formRange1[formatLen] + ',' + formRange2[formatLen] + '}';
break;

case 'n': // Number only
regEx += this.IBAN_N + '{' + formRange1[formatLen] + ',' + formRange2[formatLen] + '}';
break;

case 'c': // Alpha & number only
regEx += this.IBAN_C + '{' + formRange1[formatLen] + ',' + formRange2[formatLen] + '}';
break;
}

}else {
// It's just text to match - pass it on
regEx += matches[0];
}
//alert ('in if ' + regEx);
}else{
for (var i = 0; i < matches.length; i++) {
// Check if format or plain text
if (matches[i].indexOf('!') >= 0) {
// It's a format
var format = matches[i].split('!');
switch (format[formatType]) {
case 'a': // Alpha only
regEx += this.IBAN_A + '{' + format[formatLen].toString() + '}';
break;

case 'n': // Number only
regEx += this.IBAN_N + '{' + format[formatLen].toString() + '}';
break;

case 'c': // Alpha & number only
regEx += this.IBAN_C + '{' + format[formatLen].toString() + '}';
break;
}
} else {
// It's just text to match - pass it on
regEx += matches[i];
}
}
return regEx + '$'; // Force match to end at the end of the string
}
}

// Function: checkIban(iBan)
//  IN: Number to check - string
//  IN: Format - string (in iBan format)
// OUT: TRUE=Match; FALSE=No match
function checkStruct(iBanNum, iBanFmt) {
// Check parameters - if anything wrong return no match
if (typeof iBanNum == 'string' && iBanNum != '' && typeof iBanFmt == 'string' && iBanFmt != '') { // Looks OK do the check
// Convert the iBan format to regex string
var regExStr = convertStructToRegEx(iBanFmt);
// Convert string to RegExp();
var regEx = new RegExp(regExStr, 'gi');
//alert('iBanNum ' + iBanNum + ' iBanFmt' + iBanFmt + ' regexstr ' + regExStr + ' test ' + regEx.test(iBanNum));
// Do the test
return regEx.test(iBanNum);
}
return false; // No match or error
}

function isIBAN(s) {
var rearranged = s.substring(4, s.length) + s.substring(0, 4);
var numeric = [];
for (var i = 0; i < rearranged.length; i++) {
numeric.push((isNaN(parseInt(rearranged[i])) ? (rearranged.charCodeAt(i) - 55).toString() : rearranged[i]));
}
return mod97(numeric.join().replaceAll(',', ''));

function mod97(string) {
var checksum = string.slice(0, 2),
fragment;

for (var offset = 2; offset < string.length; offset += 7) {
fragment = String(checksum) + string.substring(offset, offset + 7);
checksum = parseInt(fragment, 10) % 97;
}

return checksum == 1;
}
}

}

 

With Regards

 

P. Siva

1 REPLY 1

Iraj Shaikh
Mega Sage
Mega Sage

Hi @Sivakrishna 

The error message you're encountering indicates that there is an attempt to access a property of an object that is undefined. The error message `TypeError: Cannot read properties of undefined (reading 'element')` suggests that the script is trying to read the `element` property of an object that hasn't been defined.

Looking at the code you've provided, the error seems to be related to the following lines:

 

var spThis = this;

// Service Portal Section
if (spThis) {
    var catItem = spThis.angular.element(spThis.$('#sc_cat_item').find('sp-variable-layout')[0]).scope();
    var parent_g_form = catItem.getGlideForm();
    parent_g_form.setValue('u_attach_reference_banking_documents', 'Yes');
}

 


The `spThis` variable is assigned the value of `this`, which is supposed to represent the current client script context. However, if this script is running in the native UI (not the Service Portal), `spThis.angular` and `spThis.$` may be undefined because they are specific to the Service Portal's AngularJS context.

To resolve this issue, you should check whether the script is running in the Service Portal or the native UI and handle each case appropriately. Here's a revised version of the code that includes a check for the Service Portal context:

 

function onSubmit() {
    // ... (rest of your code)

    // Check if running in Service Portal
    if (typeof g_form != 'undefined') {
        // Native UI context
        // Your logic for the native UI
    } else if (window.NOW && window.NOW.sp && window.NOW.sp.g_form) {
        // Service Portal context
        // Your logic for the Service Portal
        var parent_g_form = window.NOW.sp.g_form;
        parent_g_form.setValue('u_attach_reference_banking_documents', 'Yes');
    }

    // ... (rest of your code)
}

 

In this revised code, we first check if `g_form` is defined, which would indicate that the script is running in the native UI. If not, we then check if we are in the Service Portal context by looking for `window.NOW.sp.g_form`. Depending on the context, we execute the appropriate logic.

Please note that the above code is just an example and may need to be adjusted based on the actual context and requirements of your ServiceNow instance.

Please mark this response as correct or helpful if it assisted you with your question.