How to auto-populate a second field base off a string field on a table.

Chelle1
Tera Contributor

Question: How to auto-populate a second field base off a string field on a table.


Problem: The ‘Created by’ (sys_created by) field does not show the user’s name, it shows the PIV number instead. This field is also a string field.


I created a new field called ‘Created by user’ to populate the user’s name, but I am not sure what type of script to write in order to populate the already existing records with the user’s name in the ‘Created by user’ field.

 

Goal:  current.created_by_user = current.sys_created_by.name;
 
Thanks in advance.
 

 

 

4 REPLIES 4

Satishkumar B
Giga Sage
Giga Sage

Hi @Chelle1 

To auto-populate the 'Created by user' field based on 'sys_created_by', create a Business Rule (before--Insert) with this script:

 

 

(function executeRule(current, previous /*null when async*/) {
    var userGR = new GlideRecord('sys_user');
    userGR.get('user_name', current.sys_created_by);
    if (userGR.isValidRecord()) {
        current.created_by_user = userGR.name;
    }
})(current, previous);

 

 

 

……………………………………………………………………………………………………

Please Mark it helpful 👍and Accept Solution✔️!! If this helps you!!

Chelle1
Tera Contributor

Thank you for the script.  The field is not populating after running the scripts.  I will try again later and let you know the results.

 

Thanks again.

@Chelle1 Can you share me your script and the condition. also share the me the screenshot of the table form where you created the custom field.

Chelle1
Tera Contributor

I modified the script.  See below.

Table Name: Update Set (sys_update_set)

New Field Name Created on Table:  Created by name (u_name)

Source Field: Created by (sys_created_by)

 

I also created some print commands to verify if the script produced correct output; an image is also included.

Sript:

var gr = new GlideRecord('sys_update_set');

gr.addEncodedQuery('u_name.nameISEMPTY');  //Search for records with an empty field for "Created by name"

gr.query();

gs.print('Running Background Script');

 

while (gr.next()) {

        gs.print('inside the while loop');

        gr.u_name = gr.sys_created_by

    gr.form.setValue('gr.u_name',gr.sys_created_by.name);

        gr.update

        gs.print('User GR is a valid record: ' + gr.sys_created_by);

        gs.print('Created by user: ' + gr.u_name);

        gs.print('Record has been updated');

}

 

 

Results from the print commands:

*** Script: Running Background Script
*** Script: inside the while loop
*** Script: User GR is a valid record: admin
*** Script: Created by user: admin
*** Script: Record has been updated
*** Script: inside the while loop
*** Script: User GR is a valid record: admin
*** Script: Created by user: admin
*** Script: Record has been updated

Image:

Chelle1_0-1722513294560.png