create userid on the custom table

huyjor
Tera Contributor

Hello

I have a custom table with the fields for: userid, firstname and last name. If the user fills out the form for first name and last name then hit submit. I want automatically generate  the userid on the field in the table. I used business rule for this. I'm not sure why it's not generating the userid. Please help ! 

Thank You

 

When to run: After. Method: Insert

 

code below:

(function executeRule(current, previous /*null when async*/) {
 
var fname = current.first_name;
var lname = current.last_name;
 
var cal = Math.floor((Math.ramdom() * 2) +1); //Generate random number from 1-2
var username = fname+ '.'+lname +cal;
current.userid=username;
current.update();
gs.log(userid);
 
})(current, previous);
1 ACCEPTED SOLUTION

SanjivMeher
Mega Patron

Looks like there is a spelling issue

var cal = Math.floor((Math.ramdom() * 2) +1); 

instead of ramdom, use random.

You may also want run it before insert, so that you dont need a current.update().

Also may need to check, there are no existing users with the same username.

View solution in original post

6 REPLIES 6

Dr Atul - LNG
Tera Patron

Hi @huyjor 

Please chk OOTB, script on Name field

 

LearnNGrowAtul_0-1704829261462.png

 

vermaamit16
Kilo Patron

Hi @huyjor 

 

You can use below Business rule logic to avoid duplicate user ids to be generated. Also, please try and avoid using current.update() in your business rule. You can use a Before Insert Business rule with the below code to achieve this :

 

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

	// Add your code here
	var fname = current.u_first_name;
	var lname = current.u_last_name;
	var uid = fname + lname + Math.floor((Math.random() * 9999) + 1000);
	var i = 0;
	var gr = new GlideRecord('u_userrecordtable');
	while (i == 0){
	if (gr.get('u_userid', uid)){
         uid = fname + lname + Math.floor((Math.random() * 9999) + 1000);
	} else {
         i = 1;
   }
}
	current.u_userid=uid;
	//current.update();
	
	
	

})(current, previous);

 

 

Thanks & Regards

Amit Verma