How Auto populate country name in child locations

Nani18
Tera Contributor

Hello Experts,

 

In locations(cmn_location) table if location type(dropdown) = country than the name must be copied to the Country(string) attribute, including all Child records.

 

 

Nani18_0-1691586947311.png

 

before update and insert business rule is working for me but i want onload client script

 This is the business rule script
var Ltype = current.cmn_location_type.getDisplayValue();
 
    if (Ltype == 'Country') {
        current.country = current.name;
    }
    var pn = current.parent;
    var lcn = new GlideRecord('cmn_location');
    lcn.addQuery('sys_id', pn);
 
    lcn.addQuery('cmn_location_type', 'Country');
 
    lcn.query();
    if (lcn.next()) {
        current.country = pn.country;
 
 
    }

 

How to achieve this by using onload client script.

 

 

Thanks in advance,

 

Best Regards,

Nani

5 REPLIES 5

Ankur Bawiskar
Tera Patron
Tera Patron

@Nani18

if it's working with business rule then why to use client script?

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Hello @Ankur Bawiskar 

 

Business rule will work only if we update or insert any record  . I want to update existing records as well in location table. 

 

Best regards,

Nani

@Nani18 

if you want to run for existing records then you need to use fix script or background script as 1 time activity

updateRecords();

function updateRecords(){
	try{
		var gr = new GlideRecord('cmn_location');
		gr.query();
		while(gr.next()){
			var Ltype = gr.cmn_location_type.getDisplayValue();
			if (Ltype == 'Country') {
				gr.country = current.name;
			}
			var pn = current.parent;
			var lcn = new GlideRecord('cmn_location');
			lcn.addQuery('sys_id', pn);
			lcn.addQuery('cmn_location_type', 'Country');
			lcn.query();
			if (lcn.next()) {
				gr.country = pn.country;
			}
			gr.update();
		}
	}
	catch(ex){
		gs.info(ex);
	}
}

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Hello @Ankur Bawiskar 

 

Apologies,

 

Business rule is updating only one record if i make any changes manually in location form  .That means business rule also not working. Could you please help me here to achieve this requirement 

 

Thanks in advance,

 

Best regards,

Nani