Auto select the choice field depending on the value of other choice field

rohitservicenow
Mega Guru

Hello,

I am pretty new to ServiceNow need help with the sample code to auto select a choice field based on the choices selected in another field.

Suppose, I have two custom fields, A and B

A has some 50 choices and B has 10. Based on the choices selected on A, I want to auto populate the B's values.

Can we write the OnChange script / Bus rule?

Thanks,

Rohit

1 ACCEPTED SOLUTION

Please try in this way then, make sure different arrays do not have same values.



function onChange(control, oldValue, newValue, isLoading, isTemplate) {


    if (isLoading || newValue === '') {


          return;


    }


var arrayA1 = [1, 10, 15, 20, 24, 25];


var arrayA2 = [2, 6, 7, 8, 38, 49];


    //Type appropriate comment here, and begin script below


if(arrayA1.includes(parseInt(g_form.getValue('field_A'))))


g_form.setValue('field_B', '60');


if(arrayA2.includes(parseInt(g_form.getValue('field_A'))))


g_form.setValue('field_B', '70');


}


View solution in original post

19 REPLIES 19

Hi Rohit,



It's not recommended to use the current.update() in Business Rule. Can you please explain what is the use case to use Business Rule?


business wants to override the user selection while resolving the incident.


i have modified the code as below for before business rule, but its not working. Please suggest.



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




// Add your code here



var array1 = ['Application issue', 'Network issue', 'Training issue'];


var array2 = ['A','B', 'C'];


    //Type appropriate comment here, and begin script below


if(array1.includes(current.category))


current.subcategory = 'choice1';




if(array2.includes(current.category))


current.subcategory = 'choice2';




})(current,previous);


Please try with below script with suggested correction and this should help.



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


// Add your code here


var array1 = ['Application issue', 'Network issue', 'Training issue']; // I believe this should be choice value not the choice label


var array2 = ['A','B', 'C'];


if(parseInt(array1.indexOf(current.category.toString())) > -1)


current.u_description = 'choice1';


if(parseInt(array2.indexOf(current.category.toString())) > -1)


//current.u_description = 'choice2';


})(current,previous);


Hi Rohit,



are you getting those choices from any table ?


can you please share the screenshot of your field choices? i am not sure but this requirement can be achievable without using script. i would again refer my first reply . would you mind to try that .