How do I look up a user name by sys_id in widget server code?

jeremyduffy
Kilo Guru

I have a string sys_id for a user:

data.lastValidatedBy = knowledgeRecord.u_last_validated_by+"" || null;

Which is fine, but I want to print the name in the HTML. How do I convert the sys_id to a name? Would it be something like this (but altered for the user table) or is there an easier way?

var gr = new GlideRecord('change_request');
gr.addQuery('number','CHG005582); 
gr.query();
while (gr.next()) {
gr.state = 3;
gr.autoSysFields(false);   // Do not update sys_updated_on, sys_updated_by, and sys_mod_count 
gr.setWorkflow(false);       // Do not run any other business rules 
gr.update();
}
1 ACCEPTED SOLUTION

Zach N
Tera Guru

Is the knowledgeRecord variable a GlideRecord/Reference Field and u_last_validated_by a Reference Field? If so you can just dot-walk to the value you want:

var name = knowledgeRecord.u_last_validated_by.name;

 

If u_last_validated_by is just a string with the Sys ID, then yes you will have to look up the record. Try something like this:

var gr = new GlideRecord('sys_user');
if (gr.get(knowledgeRecord.u_last_validated_by))
    var name = gr.name;

 

Hope that helps!

 

View solution in original post

3 REPLIES 3

Zach N
Tera Guru

Is the knowledgeRecord variable a GlideRecord/Reference Field and u_last_validated_by a Reference Field? If so you can just dot-walk to the value you want:

var name = knowledgeRecord.u_last_validated_by.name;

 

If u_last_validated_by is just a string with the Sys ID, then yes you will have to look up the record. Try something like this:

var gr = new GlideRecord('sys_user');
if (gr.get(knowledgeRecord.u_last_validated_by))
    var name = gr.name;

 

Hope that helps!

 

Oh yeah! It's that easy!? I tested it and it works. Thank you!

Of course! Glad it worked!