correct me that javascript is wrong

venkyc
Kilo Contributor

@RakeshDarshnala 

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue === oldValue) {
        return;
    }

if (newValue === 'Closed') {
  g_form.showFieldMsg('state','Cannot close directly. Please follow the proper workflow.' );
  g_form.setValue('state', oldValue);
}
2 REPLIES 2

SohamTipnis
Tera Guru

Hi @venkyc,

 

There is 1 issue I found out: in the loop of if, where you have used 'Closed,' you should use 7, as 'Closed's backend name is 7. That is the issue you are facing.

 

Let me know if this works. 👍

If you find my answer useful, please mark it as Helpful and Correct 😊

 

Regards,

Soham Tipnis

ServiceNow Developer ||  Technical Consultant

LinkedIn: www.linkedin.com/in/sohamtipnis10

 

BhagyashriA
Tera Contributor
Hi @venkyc

Please find the solution below.

Since the State field uses a numeric backend value, assume the value for Closed is 7. To prevent users from closing the record directly, this can be handled either through a UI Policy / Client Script or enforced using a Business Rule.

Option 1: Client Script (UI-level control)

An onChange client script can be used to display a message when the user selects Closed:

function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === oldValue) {
return;
}

if (newValue === 7) {
g_form.showFieldMsg(
'state',
'Cannot close directly. Please follow the proper workflow.',
'error'
);
}
}


Note: This approach only affects the form UI and does not prevent updates via list edit, imports, or APIs.

Option 2: Business Rule (recommended for enforcement)

To fully abort the action when the state is changed to Closed, use a Before Update Business Rule:

(function executeRule(current, previous) {

gs.addErrorMessage(
'You cannot close this record directly. Please follow the proper workflow.'
);
current.setAbortAction(true);

})(current, previous);

Let me know if it works.