Automatically set the value of a field base on system user when creating new record in a table

cindy_huang
Tera Contributor
As stated in the subject, I am trying to set the value of a field based on the current system username when creating a new record. I tried calculated value tab in the dictionary entry to return current user name. However, the field value is blank when I create a new record. It works fine after the record is created. Also, I tried scripted Background and made sure that "createName" print out the correct value. The following code is how I calculated the value, I need some help to find out what is wrong with it.
 
(function calculatedFieldValue(current) {
    // if current GlideRecord is new record
    if (current.isNewRecord()) {
        // the field value = INV_sysuserName
        var createName = "INV_" + gs.getUserName().toUpperCase();
        return (createName); // return the calculated value
    } else {
        var userName = "INV_" + current.getValue('sys_created_by').toUpperCase();
        return (userName); // return the calculated value
    }
})(current);
1 ACCEPTED SOLUTION

OlaN
Giga Sage
Giga Sage

Hi,

A calculated value in ServiceNow is exactly that. It's calculated whenever a record is shown, in a list or on a form for example. Therefore must be used with caution, because it can have severe impact on your instance performance.

 

If your aim is to set the value of a field at creation-time of a record, I would suggest that you either implement a business rule, that runs on insert, and has the same script, just add a line to set the value to the correct field.

Or you can try setting the value as a default value on the dictionary entry.

View solution in original post

4 REPLIES 4

OlaN
Giga Sage
Giga Sage

Hi,

A calculated value in ServiceNow is exactly that. It's calculated whenever a record is shown, in a list or on a form for example. Therefore must be used with caution, because it can have severe impact on your instance performance.

 

If your aim is to set the value of a field at creation-time of a record, I would suggest that you either implement a business rule, that runs on insert, and has the same script, just add a line to set the value to the correct field.

Or you can try setting the value as a default value on the dictionary entry.

cindy_huang
Tera Contributor

Hi OlaN,

Thanks for the advise, I put the script in the default value and it functioned as desired. 

J Siva
Tera Sage

Hi @cindy_huang 
You need to use a 'Before Insert' business rule to automatically populate the field value.

Regards,
Siva

Hi Siva, 

Thanks for the advice. The before insert is a good way, but it does not populate value before the user click submit which the client required. I tried putting the script in the default value and it went well. I will adapt the BR method in another field that is read-only and is not required to display before creating.