How to check if a List field has only one record using a client script?

CharlesR1
Kilo Guru

Hello all,

On Table 'proc_po' we have a requirement to populate a reference field 'u_final_category_detail' which references the table 'u_final_category_detail'.

Table 'proc_po' also has the reference field 'u_cost_center', which references the table 'cmn_cost_center'.

Table 'cmn_cost_center' has a List field 'u_final_category_detail' which is referencing Table 'u_final_category_detail'.

The requirement is to populate the reference field 'u_final_category_detail' on the 'proc_po' table only if there is only one entry in the list field on table 'cmn_cost_center'.

How do we amend the following script to check for only one entry on the list field?

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

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

          return;

    }

var category = g_form.getValue('u_cost_center);

var category1 = new GlideRecord('cmn_cost_center');

category1.addQuery('sys_id', category);

//We need a script here to check to check if the 'u_final_category_detail' list field has only one entry, and only to proceed if so.

category1.query();

if(category1.next()){

    g_form.setValue('u_final_category_detail' , category1.u_final_category_detail);

  }

}

Thanks very much for any help.

Charles

1 ACCEPTED SOLUTION

anurag92
Kilo Sage

Modifying a part of your code:



var category = g_form.getValue('u_cost_center);


var category1 = new GlideRecord('cmn_cost_center');


category1.addQuery('sys_id', category);




//We need a script here to check to check if the 'u_final_category_detail' list field has only one entry, and only to proceed if so.


category1.query();





if(category1.next() && category1.u_final_category_detail.split(',').length == '1'){



    g_form.setValue('u_final_category_detail' , category1.u_final_category_detail);



  }


}


View solution in original post

5 REPLIES 5

Ahmed Hmeid1
Kilo Guru

List fields stores values as a comma separated list of sys_ids.



So you could do this:



var fC = g_form.getValue('u_final_category_detail');


fCArray = fC.split(',');


if (fcArray.length == 1) {


//do what you gotta do


}


anurag92
Kilo Sage

Modifying a part of your code:



var category = g_form.getValue('u_cost_center);


var category1 = new GlideRecord('cmn_cost_center');


category1.addQuery('sys_id', category);




//We need a script here to check to check if the 'u_final_category_detail' list field has only one entry, and only to proceed if so.


category1.query();





if(category1.next() && category1.u_final_category_detail.split(',').length == '1'){



    g_form.setValue('u_final_category_detail' , category1.u_final_category_detail);



  }


}


Perfect! Thanks Anurag!


I just wanted to point out that you should not write client gliderecord queries directly on client side objects. This is a ServiceNow best practice violation and will shown up on your ACE report.