Create unique username

kennethandersen
Kilo Contributor

I will like to use the transform map to create a unique username from firstname an lastname plus a number 3+3+4

So a name like this

Ex. 1 # Lars Larsen will be LAR (3 from firstname) LAR (3 from lastname) 1985 (a random number)

So the username is LARLAR1985

Ex. 2 # Lars W. Larsen will be LAR (3 from firstname) LAR (3 from lastname) 1985 (a random number)

So the username is LARLAR1856

But before the creating of the username, it have to check the sys_user table if the username is already where.

Hope you got the idea

1 ACCEPTED SOLUTION

With the assumptions that the import only creates new user records and the first and last field names try this in a field map script.



var first = source.u_firstname.slice(0,3);


var last = source.u_lastname.slice(0,3);


var uid = first + last + Math.floor((Math.random() * 9999) + 1000);




var i = 0;


var gr = new GlideRecord('sys_user');


while (i == 0){


  if (gr.get('user_name', uid)){


        uid = first + last + Math.floor((Math.random() * 9999) + 1000);


  } else {


        i = 1;


  }


}



answer = uid;


View solution in original post

8 REPLIES 8

Give it a shot when defining first and last.


Goran WitchDoc
ServiceNow Employee
ServiceNow Employee

U can achieve this is a transform script. Make a onBefore and do the check, and before you decide on the name, you do a query to the usertable to see if it already exist. If not, use it, otherwise just add "reroll" the random number and check again.



//Göran


kennethandersen
Kilo Contributor

Maybe like this ?





String.prototype.cleanup = function() {


      return this.toLowerCase().replace(/[^a-z']/g, '');


};




var first = source.u_firstname.slice(0,3).cleanup();


var last = source.u_lastname.slice(0,3).cleanup();


var uid = first + last + Math.floor((Math.random() * 9999) + 1000);




var i = 0;


var gr = new GlideRecord('sys_user');


while (i == 0){


      if (gr.get('user_name', uid)){


              uid = first + last + Math.floor((Math.random() * 9999) + 1000);


      } else {


              i = 1;


      }


}



answer = uid;


SaschaWildgrube
ServiceNow Employee
ServiceNow Employee

If you also want to limit to total length of the user name, this function may be helpful:

https://github.com/saschawildgrube/servicenow-devtools/blob/master/update/sys_script_include_48b84c2...

The DevTools app contains a truckload of reusable scripts and
features to support your app development.

Fork at will!