How to Autopopulate the Manager's Email Address in a ServiceNow Form
When designing forms in ServiceNow, it's common to need certain fields to automatically populate based on user selections. A frequently encountered requirement is autopopulating a manager's email address when a manager is selected. Here’s a straightforward method to achieve this using Client Scripts and getReference in ServiceNow.
You have a form with two fields:
- Manager (Reference field): referencing the User table (sys_user).
- Manager Email (String field): intended to store the email address of the selected manager.
Recommended Solution
Use an On-Change Client Script with a getReference callback to fetch and populate the manager’s email address automatically when the manager field changes.
Step-by-Step Implementation
- Create an On-Change Client Script:
Navigate to: System Definition → Client Scripts and create a new client script.
Set the following properties:
- Type: OnChange
- Table: Your specific table
- Field Name: Manager (or your reference field's name)
- Script Content:
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') {
return;
}
// Fetch the manager's record
g_form.getReference('manager', getEmail);
function getEmail(manager) {
// Populate the email address field with manager's email
g_form.setValue('manager_email', manager.email);
}
}
Explanation:
- getReference retrieves the full manager record.
- The callback function getEmail is invoked once the record is retrieved.
- g_form.setValue sets the email field to the manager's email.
Alternative Approaches
If you'd prefer other methods, here are alternatives:
- Dot-Walking: Directly dot-walk from the manager reference field to the email attribute (manager.email).
- GlideAjax: Use GlideAjax if additional server-side logic is needed before populating.
Recommendations
- Prefer simple approaches like getReference or dot-walking unless complex logic is required.
- Ensure fields referenced (manager, manager_email) are accurately named to avoid confusion.
Implementing these steps will help efficiently autopopulate the manager’s email address and enhance user convenience and data accuracy on your forms.