- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-09-2024 11:34 AM
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:
Solved! Go to Solution.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-09-2024 11:40 AM
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.
Please mark this response as correct or helpful if it assisted you with your question.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-09-2024 11:41 AM
Hi @huyjor
Please chk OOTB, script on Name field
If my response proves useful, please indicate its helpfulness by selecting " Accept as Solution" and " Helpful." This action benefits both the community and me.
Regards
Dr. Atul G. - Learn N Grow Together
ServiceNow Techno - Functional Trainer
LinkedIn: https://www.linkedin.com/in/dratulgrover
YouTube: https://www.youtube.com/@LearnNGrowTogetherwithAtulG
Topmate: https://topmate.io/atul_grover_lng [ Connect for 1-1 Session]
****************************************************************************************************************
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
01-09-2024 10:31 PM - edited 01-09-2024 10:31 PM
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
Please mark this response as correct and helpful if it assisted you with your question.