Auto-increment string value

ashishpanda88
Tera Contributor

Hi,

We have a requirement where we need to store a location code in the cmn_location table for USA location. This attribute should be blank for all locations except USA. Only when the country is chosen as USA, the field should get auto-populated. The code should be unique and auto-incremented everytime for a new location.

The code should always be 3-digit and goes as below:

4Y0
4Y1
4Y2
.
.
.
4Y9
4Z0
4Z1
4Z2
.
.
.
4Z9
5A0
5A1

and so on.

Can anyone please help me with the script for this requirement?

1 ACCEPTED SOLUTION

Gowrisankar Sat
Tera Guru

Hi Ashish,



I did a similar kind of research a few days back, but I tried to build code on my own, below is a raw modified code as per your requirement. You should write this in a onInsert Business Rule:




var gr = new GlideRecord('cmn_location');


gr.addQuery('u_unique_id1!=NULL'); //unique_id1 is the field I used


gr.orderByDesc('u_unique_id1');


gr.query();


if(gr.next())


{


var str = gr.u_unique_id1;


var res = str.substring(2, 3); //check for last value


var resnum = parseInt(res,10);


if(resnum == 9 && str.charCodeAt(1) == "Z") //if last two values are Z9, set A0 and increment the first digit


{


var fir = str.substring(0, 1); //increment the first one


var firnxt = parseInt(fir,10);


firnxt = firnxt+1;


var nextalpupd = firnxt+'A0';


current.u_unique_id1 = nextalpupd;


}


else if(resnum == 9 && str.charCodeAt(1) != "Z") //if last two values are G9, set H0


{


var firnum = str.substring(0, 1);


var nextnumalp = str.charCodeAt(1);


var nextnumalpupd = String.fromCharCode(++nextnumalp);


var totalval = firnum + nextnumalpupd +'0';


current.u_unique_id1 = totalval;


}


else if(resnum <9 && str.charCodeAt(1) != "Z") //if last two values are B8, set B9


{


var firsttwostr = str.substring(0, 2);


var lastres = str.substring(2, 3);


var lastscen = parseInt(lastres,10);


var lastscnum = lastscen+1;


var totalvals =firsttwostr +lastscnum;


current.u_unique_id1 = totalvals;


}


else


{


current.u_unique_id1 = '0A0';


}


}


View solution in original post

5 REPLIES 5

andrew_venables
ServiceNow Employee
ServiceNow Employee

Why not use the ootb number maintenance?




You can create a new number record and then set the default of the field to contain an if statement that only returns if in the US.




Much simpler and easier to maintain as no customer code is needed.