To achieve the goal of copying the selected values from two choice variables (User and Company) into a single string field once both selections are made, we can use a Client Script in ServiceNow. For this scenario, an onChange client script would be ideal to trigger actions when the value of either the User or the Company field changes.
Here's a simplified approach on how you can set this up:
1. Understanding the Variables
- Variable 1: Let's assume the variable name for the User is
user.
- Variable 2: And for the Company, the variable name is
company.
- Target String Field: The field where you want to copy the combined data, let's call it
combinedField for now. This could be a custom field that you've added to the form.
2. Client Script
You'll want to create a new Client Script that triggers onChange of both the User and Company fields. Here's a basic template to get you started:
Script Type: onChange
Applies to: Catalog Item/Record Producer as needed
Field Name: This script will be applied to both user and company. You'll need to create a separate onchange script for each, or you can use the function onChange(control, oldValue, newValue, isLoading, isTemplate) structure to program based on the control parameter identifying which field has changed.
Script:
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
// Make sure this runs only when both the user and company have values
var user = g_form.getValue('user');
var company = g_form.getValue('company');
if (user && company) {
// Fetching display values instead of sys_ids for user-friendly names
var userName = g_form.getDisplayBox('user').value;
var companyName = g_form.getDisplayBox('company').value;
// Constructing the string
var combinedValue = 'User ' + userName + ' Company ' + companyName;
// Setting the constructed string to the target field
g_form.setValue('combinedField', combinedValue);
}
}
Points to Consider:
- Ensure that you replace
user, company, and combinedField with the actual variable names used in your ServiceNow instance.
- This script utilizes
getDisplayBox().value to fetch the display value (user-friendly name) of reference fields; adjust as necessary based on your specific implementation and variable types.
- Test this script thoroughly in a development environment to make sure it behaves as expected, particularly paying attention to edge cases like one of the fields being cleared after both have been initially set.
This should provide a solid starting point for combining selections from two choice/reference fields into a string value in a third field upon selection. Remember, the effectiveness of the script can vary based on the exact configuration of your Catalog Item/Record Producer and the fields involved, so adjustments might be necessary.