How to autopopulate name of logged in user in field on a form?

Aditya Sinha
Tera Contributor

I have a form where a field needs to be populated with name of logged in user.  I am using an on load script however it is not working, (I have checked the UI type to ALL).

 

function onLoad() {
   //Type appropriate comment here, and begin script below
   var gq=new GlideRecord("sys_user");
   //alert((g_form.getReference(g_user.userID)));
   var ab=g_user.userID;
   
   gq.addQuery("user_name",ab);
   gq.query();
   

   g_form.setValue("field name",gq.name);

   
}
11 REPLIES 11

function onLoad() {
// Get the current user's email
var userEmail = g_user.getEmail();

// Set the value of the field
g_form.setValue('field_name', userEmail);
}

make modification as per your need

SANDEEP28
Mega Sage

@Aditya Sinha Please remember you should not do GlideRecord operations in client script without callback function. You requirement is simple and it is achievable using "g_user" client side API without GlideRecord operations. Always make sure to check what all OOB API's are available at client side and server side. 

 

function onLoad() {
// g_user.getFullName() will give you first & last name of user
g_form.setValue('field_name', g_user.getFullName());
}

Go to script section of client script and press "control" & "spacebar", you will get all available client side API's 

 

If I could help you with your Query then, please hit the Thumb Icon and mark as Correct !! 

Hey Sandeep. What if 2 users have the same full name? Wouldn't fetching the sys_id and then the corresponding name to the sys_id from the sys_user table be a more prudent solution to avoid such a case?

@Aditya Sinha You want  logged in User name right ? So there will be only one user.

"g_user.getFullName()" method will internally take sys ID of logged in User and return Full name of logged in User.

So don't worry about it 🙂

 

If I could help you with your Query then, please hit the Thumb Icon and mark as Correct !! 

 

Aah Yes! My bad. Thank you