in servicenow catalog item i need to set the reference variable values based on the selectbox field value
Assistant
In ServiceNow, setting the value of a reference variable based on a select box field can typically be achieved by using Client Scripts. Here’s a general approach to accomplish this:
Steps to Set Reference Variable Values Based on Select Box Field Value
Create the Select Box Variable:
Go to the Catalog Item where you want to add the variables.
Create a new variable of type Select Box. For example, name it select_box_variable.
Create the Reference Variable:
Create a new variable of type Reference. Set the Reference Table (Table field) to the appropriate table you want to refer to (e.g., User, Group, etc.). Name it reference_variable.
Add a Client Script:
In the same Catalog Item, create a new Client Script.
Set the Type to onChange and set the Variable name to your select_box_variable.
Use the following code as a template to dynamically set the reference variable value based on what is selected in the select box:
javascript
// onChange Client Script for Select Box Variable
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') {
return;
}
// Define a mapping between select box options and reference values
var referenceValue;
// Example: Change this to your actual logic
if (newValue === 'Option1') {
referenceValue = 'sys_id_of_reference1'; // Replace with actual sys_id
} else if (newValue === 'Option2') {
referenceValue = 'sys_id_of_reference2'; // Replace with actual sys_id
} else {
referenceValue = ''; // Default case
}
// Set the value of the reference variable
g_form.setValue('reference_variable', referenceValue);
}
Important Notes
Replace sys_id_of_reference1 and sys_id_of_reference2 with actual sys_ids of the records you want to reference. You can obtain these sys_ids by checking the record in the respective table you’re referencing.
Ensure that the name of the reference_variable matches what you use in the g_form.setValue() method.
If your select box options are dynamic (e.g., populated from another table), ensure that the logic to derive referenceValue from newValue correlates correctly to the selected values.
You may also need to adjust your business logic depending on the specific needs of your catalog item.
Testing
After saving the changes, test your catalog item by selecting different options in the select box. The reference variable should update automatically based on the selection.
Additional Enhancements
You can also fetch the desired reference values from the server-side if they depend on complex logic or are not known at the time of the client-side execution. This can be done using a GlideAjax call to a Script Include.
By following these steps, you can effectively manage and set reference variable values based on user selections in a ServiceNow catalog item.
User
i cant pass the sys id, i need to do it via script include and onchange client script
Assistant
To achieve setting a reference variable value dynamically using a Script Include and an onChange Client Script in ServiceNow, follow these steps:
1. Create the Script Include
First, create a Script Include that will fetch the necessary reference value based on the input from the select box.
Steps to Create Script Include:
In the Application Navigator, search for Script Includes and click on it.
Click on New to create a new Script Include.
Fill out the form with the following information:
Name: ReferenceValueProvider (or any name you prefer)
API: Make sure that "Client Callable" is checked.
Script:
javascript
var ReferenceValueProvider = Class.create();
ReferenceValueProvider.prototype = {
initialize: function() {},
getReferenceSysId: function(selectValue) {
// Logic to determine sys_id based on selectValue
var sysId = '';
if (selectValue === 'Option1') {
sysId = 'sys_id_of_reference_value_1'; // Replace with actual sys_id
} else if (selectValue === 'Option2') {
sysId = 'sys_id_of_reference_value_2'; // Replace with actual sys_id
}
// Add more conditions as needed here
return sysId; // Return the computed sys_id or an empty string
},
type: 'ReferenceValueProvider'
};
2. Create the onChange Client Script
Next, you will create an onChange Client Script for your select box variable that calls the Script Include to get the correct sys_id.
Steps to Create onChange Client Script:
In your Catalog Item, navigate to the Variables section.
Open (or create) the onChange Client Script related to your select box variable (select_box_variable).
Use the following script as a template:
javascript
User
PLease correct my script include and client script
Script Include:
var GetCIServiceForCatalog = Class.create();
GetCIServiceForCatalog.prototype = Object.extendsObject(AbstractAjaxProcessor, {
code
getServiceRecord: function() {
var selectValue = this.getParameter('selectValue'); // Get the value passed from the client script
var serviceRecord = {}; // Use an object to store the sys_id
var gr = new GlideRecord('cmdb_ci_service');
// Apply conditions based on the select value
if (selectValue == 'salehubplus') {
// Query the table for the record with this specific name
gr.addQuery('name', 'SALESHUB+ - HANDHELDNEXT - SO');
} else if (selectValue == 'salesproplus') {
// Query the table for the record with this specific name
gr.addQuery('name', 'SALESPRO+ - SO');
}
// Query the cmdb_ci_service table
gr.query();
// Check if a matching record is found
if (gr.next()) {
// Return the sys_id of the found record
serviceRecord.sys_id = gr.getValue('sys_id');
}
// Return the sys_id as a JSON string (empty if no match found)
return JSON.stringify(serviceRecord);
},
type: 'GetCIServiceForCatalog'
});
Client Script:
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
code
var selectedValue = g_form.getValue('app_name'); // Get the selected value from the select box field
// If a valid value is selected, call the Script Include to get the corresponding sys_id
if (selectedValue) {
var ga = new GlideAjax('GetCIServiceForCatalog');
ga.addParam('function', 'getServiceRecord'); // Call the function in the Script Include
ga.addParam('selectValue', selectedValue); // Pass the selected value to the Script Include
ga.getXMLAnswer(function(response) {
var serviceRecord = JSON.parse(response); // Parse the response to extract sys_id
// Check if the sys_id is valid (not empty or undefined)
if (serviceRecord && serviceRecord.sys_id) {
// Set the reference field with the found service record sys_id
g_form.setValue('service_offering', serviceRecord.sys_id);
} else {
// If no record is found, clear the reference field (optional)
g_form.setValue('service_offering', '');
}
g_form.setValue('service_offering', ''); // Clear the field in case of error
});
}
}
Assistant
Your Script Include and Client Script are very close to being correct. I see a few minor issues and improvements that can enhance the code. Here's a corrected version for both.
Updated Script Include
The method name in addParam should match the function name.
Return the sys_id directly without wrapping it in an object for simplicity.
Here’s the revised Script Include:
javascript
var GetCIServiceForCatalog = Class.create();
GetCIServiceForCatalog.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getServiceRecord: function() {
var selectValue = this.getParameter('selectValue'); // Get the value passed from the client script
var serviceRecord = ''; // Use a string to store the sys_id (not an object)
var gr = new GlideRecord('cmdb_ci_service');
// Apply conditions based on the select value
if (selectValue === 'salehubplus') {
gr.addQuery('name', 'SALESHUB+ - HANDHELDNEXT - SO'); // Query for this specific name
} else if (selectValue === 'salesproplus') {
gr.addQuery('name', 'SALESPRO+ - SO'); // Query for this specific name
}
// Query the cmdb_ci_service table
gr.query();
// Check if a matching record is found
if (gr.next()) {
// Return the sys_id of the found record
serviceRecord = gr.getValue('sys_id');
}
// Return the sys_id as a plain string (empty if no match found)
return serviceRecord || '';
},
type: 'GetCIServiceForCatalog'
});
Updated Client Script
Use newValue directly for the selected value.
The g_form.setValue('service_offering', ''); after processing should only be used in the error case.
User
it is populating wrong value and if i select option 1 again it is not working
Assistant
If the script is not populating the expected values and you experience issues when selecting the option again, it can often be due to a couple of reasons: incorrect logic in the Script Include or the Client Script accessing the wrong value.
Debugging Steps
Check Select Box Values: Ensure that the values you are comparing in the Script Include (salehubplus, salesproplus, etc.) are exactly the same as the values present in the select box. Any mismatch (case sensitivity or whitespace) can cause issues.
Log Debug Information: Adding logs to see the flow of data can be very helpful to determine what's being passed and what's returned. Here's how you can do it:
Updated Script Include with Logging
Add some logging to trace the values being passed and the results you obtain.
javascript
var GetCIServiceForCatalog = Class.create();
GetCIServiceForCatalog.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getServiceRecord: function() {
var selectValue = this.getParameter('selectValue'); // Get the value passed from the client script
var serviceRecord = ''; // Store the sys_id as a string
var gr = new GlideRecord('cmdb_ci_service');
// Logging the received selectValue to debug
gs.info('Received selectValue: ' + selectValue); // Log the value
// Apply conditions based on the select value
if (selectValue === 'salehubplus') {
gr.addQuery('name', 'SALESHUB+ - HANDHELDNEXT - SO'); // Query for this specific name
} else if (selectValue === 'salesproplus') {
gr.addQuery('name', 'SALESPRO+ - SO'); // Query for this specific name
}
gr.query();
if (gr.next()) {
serviceRecord = gr.getValue('sys_id'); // Get sys_id of the found record
gs.info('Found sys_id: ' + serviceRecord); // Log found sys_id
} else {
gs.info('No records found for selectValue: ' + selectValue); // Log if no records found
}
return serviceRecord || ''; // Return the sys_id or empty string
},
type: 'GetCIServiceForCatalog'
});
User
i do not want to trim the white spaces
Assistant
If you do not want to trim the whitespace from the response returned by the Script Include, you can simply remove the trim() function from your current code.
Here’s the revised code for both the Script Include and the Client Script that avoids trimming the whitespace:
Updated Script Include
There are no changes needed in the Script Include to remove trimming, but I'll provide it here for completeness with the logging included:
javascript
var GetCIServiceForCatalog = Class.create();
GetCIServiceForCatalog.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getServiceRecord: function() {
var selectValue = this.getParameter('selectValue'); // Get the value passed from the client script
var serviceRecord = ''; // Store the sys_id as a string
var gr = new GlideRecord('cmdb_ci_service');
// Logging the received selectValue to debug
gs.info('Received selectValue: ' + selectValue); // Log the value
// Apply conditions based on the select value
if (selectValue === 'salehubplus') {
gr.addQuery('name', 'SALESHUB+ - HANDHELDNEXT - SO'); // Query for this specific name
} else if (selectValue === 'salesproplus') {
gr.addQuery('name', 'SALESPRO+ - SO'); // Query for this specific name
}
gr.query();
if (gr.next()) {
serviceRecord = gr.getValue('sys_id'); // Get sys_id of the found record
gs.info('Found sys_id: ' + serviceRecord); // Log found sys_id
} else {
gs.info('No records found for selectValue: ' + selectValue); // Log if no records found
}
return serviceRecord || ''; // Return the sys_id or empty string
},
type: 'GetCIServiceForCatalog'
});
User
simply if variable has value onion then i need to glide record the cmdb_ci_service table and query for the name and return that name and set it to that field only
Assistant
If you simply want to perform a GlideRecord query on the cmdb_ci_service table based on a single variable value (e.g., you want to check if the value is "onion"), and then return the corresponding name of the record to set it in a specific field, you can follow these steps:
Step 1: Modify the Script Include
This Script Include should query the cmdb_ci_service table for the record that matches the input value (in this case, "onion") and return its name.
Script Include Code
javascript
var GetCIServiceForCatalog = Class.create();
GetCIServiceForCatalog.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getServiceRecord: function() {
var selectValue = this.getParameter('selectValue'); // Get the value passed from the client script
var serviceName = ''; // Initialize variable to hold the result
// Only perform query if the input value matches "onion"
if (selectValue === 'onion') {
var gr = new GlideRecord('cmdb_ci_service');
gr.addQuery('name', 'onion'); // Adjust according to your actual name
gr.query();
// Check if a matching record is found
if (gr.next()) {
serviceName = gr.getDisplayValue('name'); // Get the name of the service
}
}
return serviceName; // Return either the found name or an empty string
},
type: 'GetCIServiceForCatalog'
});
Step 2: Modify the Client Script
This Client Script should call the Script Include when the variable changes, then set the returned name to the designated field.
Client Script Code
javascript
Not yet included in a published release.
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') {
return;
}
// Create a GlideAjax object
var ga = new GlideAjax('ReferenceValueProvider');
ga.addParam('sysparm_name', 'getReferenceSysId'); // Name of the function in Script Include
ga.addParam('sysparm_select_value', newValue); // Pass the value of the selected option
// Execute the call and get the response
ga.getXMLAnswer(function(response) {
var sysId = response; // Get the returned sys_id from the Script Include
// Set the reference variable using the returned sys_id
g_form.setValue('reference_variable', sysId);
});
}
Important Considerations:
Replace the sys_ids: In the Script Include, make sure to replace the placeholder sys_ids with the actual sys_ids from your table.
Ensure Script Include is Client Callable: Make sure that the "Client Callable" checkbox is checked for the Script Include you created.
Modify Logic As Needed: Modify the logic in the Script Include’s getReferenceSysId method to fit the actual business requirements and mappings.
Ensure Proper Deployment: Test these changes in a development environment before moving to production to ensure they are functioning as expected.
Testing
Navigate to the catalog item containing your select_box_variable.
Change the option in the select box and check if the reference variable updates as intended based on your selections.
By following these instructions, you can successfully use a Script Include to dynamically set reference variable values based on the selected option from a select box in ServiceNow.
Here’s the revised Client Script:
javascript
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') {
return;
}
// Use newValue directly from the onchange handler
var selectedValue = newValue; // Get the new value directly from the onChange event
// If a valid value is selected, call the Script Include to get the corresponding sys_id
if (selectedValue) {
var ga = new GlideAjax('GetCIServiceForCatalog');
ga.addParam('sysparm_name', 'getServiceRecord'); // Call the function in the Script Include
ga.addParam('selectValue', selectedValue); // Pass the selected value to the Script Include
ga.getXMLAnswer(function(response) {
// No need to parse JSON here since the response is directly the sys_id
var sysId = response.trim(); // Get the response and trim any whitespace
// Check if the sys_id is valid (not empty)
if (sysId) {
// Set the reference field with the found service record sys_id
g_form.setValue('service_offering', sysId);
} else {
// If no record is found, clear the reference field
g_form.setValue('service_offering', '');
}
});
}
}
Summary of Key Changes:
Script Include:
Changed the return value from an object to a string representing the sys_id.
Client Script:
Used newValue directly without calling g_form.getValue().
Corrected the name in ga.addParam('function', ... to ga.addParam('sysparm_name', ....
Removed the unnecessary line that clears the reference field at the end.
Testing
After making these adjustments, test the functionality of the Catalog Item containing your select box and reference variable. When a value is selected, the reference variable should correctly populate with the corresponding sys_id based on the logic you defined in your Script Include.
Updated Client Script with Logging
Add logging to the Client Script to confirm which value is being selected.
javascript
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') {
return;
}
var selectedValue = newValue; // Use newValue directly from the onChange event
console.log('Selected value: ' + selectedValue); // Log the selected value
if (selectedValue) {
var ga = new GlideAjax('GetCIServiceForCatalog');
ga.addParam('sysparm_name', 'getServiceRecord'); // Call the function in the Script Include
ga.addParam('selectValue', selectedValue); // Pass the selected value to the Script Include
ga.getXMLAnswer(function(response) {
console.log('Response from Script Include: ' + response.trim()); // Log the response from the server
var sysId = response.trim(); // Trim whitespace
if (sysId) {
g_form.setValue('service_offering', sysId);
console.log('Reference field populated with sys_id: ' + sysId); // Log successful population
} else {
g_form.setValue('service_offering', '');
console.log('No sys_id found, clearing reference field.'); // Log clearing
}
});
}
}
Additional Considerations
Cache Issues: Ensure that there are no caching issues which might affect the behavior. You can either clear browser cache or try using a different browser altogether.
Check for Multiple Client Scripts: Sometimes multiple Client Scripts can interfere with each other. Ensure that there are no other Client Scripts on the same catalog item manipulating the same references.
Testing: After making these updates, monitor the logs in ServiceNow (System Logs > All) to see your debugging info. Confirm that the correct values are being passed to your Script Include and that it is returning the expected sys_id.
Refresh Logic: If you’re seeing that selecting the same option again does not trigger the change, ensure that g_form.setValue() is not inadvertently setting a value that prevents the onChange from firing. You might need to force-reset the field if that behavior continues.
Conclusion
With these logs, you should be able to see the flow of values and identify whether the issue lies in value comparisons, the GlideRecord query, or how the response is processed. Adjust any logic according to what the logs reflect regarding the actual values being passed and returned.
Updated Client Script
Here’s the updated Client Script without any trimming:
javascript
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') {
return;
}
var selectedValue = newValue; // Use newValue directly from the onChange event
console.log('Selected value: ' + selectedValue); // Log the selected value
if (selectedValue) {
var ga = new GlideAjax('GetCIServiceForCatalog');
ga.addParam('sysparm_name', 'getServiceRecord'); // Call the function in the Script Include
ga.addParam('selectValue', selectedValue); // Pass the selected value to the Script Include
ga.getXMLAnswer(function(response) {
console.log('Response from Script Include: ' + response); // Log the response from the server
// Using the raw response without trimming
var sysId = response;
if (sysId) {
g_form.setValue('service_offering', sysId);
console.log('Reference field populated with sys_id: ' + sysId); // Log successful population
} else {
g_form.setValue('service_offering', '');
console.log('No sys_id found, clearing reference field.'); // Log clearing
}
});
}
}
Key Points
Whitespace Management: The response variable comes directly from the server without any trimming, meaning if the server returns a value with leading/trailing whitespace, it will be preserved.
Debugging and Testing: Maintain your logging statements as they will assist in tracking what values are being passed and returned.
Validate Input: Ensure that the values from the select box do not have unintentional whitespace which would affect the logic (for example, ' salehubplus' vs. 'salehubplus').
Validate Before Use
Make sure to check that:
The select box values (salehubplus, salesproplus etc.) correspond exactly to what you are using in your Script Include for comparisons—especially considering any additional whitespace.
That you don't inadvertently introduce whitespace into your select box options or in the values from your cmdb_ci_service table names.
By maintaining the values as they are, including any whitespace, you ensure fidelity to the original data. Test thoroughly and monitor the logs to diagnose any issues with selected values.
function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue === '') {
return; // Exit if it's the initial load or no new value
}
var selectedValue = newValue; // Get the selected value from the change event
console.log('Selected value: ' + selectedValue); // Log the selected value
// Call the Script Include to get the corresponding service name
var ga = new GlideAjax('GetCIServiceForCatalog');
ga.addParam('sysparm_name', 'getServiceRecord'); // Call the function in the Script Include
ga.addParam('selectValue', selectedValue); // Pass the selected value to the Script Include
ga.getXMLAnswer(function(response) {
console.log('Response from Script Include: ' + response); // Log the response from the server
// If a name was returned, set that value in the desired field
if (response) {
g_form.setValue('field_name_to_set', response); // Change 'field_name_to_set' to your actual field name
console.log('Field populated with: ' + response); // Log successful population
} else {
g_form.setValue('field_name_to_set', ''); // Optionally clear the field if no name found
console.log('No service found, clearing the field.'); // Log clearing
}
});
}
Key Points to Consider:
Adjust the Name in the Query: In the Script Include, if you want to look for a specific name in the cmdb_ci_service table, you can change the condition in the addQuery() method accordingly. Replace 'onion' with the exact name you want to query.
Field Names: Ensure that you replace 'field_name_to_set' in the Client Script with the actual name of the field where you want to display the returned service name.
Testing: Verify that the functionality works as expected. When you change the relevant catalog variable, the script should execute and set the appropriate name based on your specified logic in the Script Include.
Logging: The console.log statements can help you trace if the right values are being passed and if your record is fetched correctly.
No Passing of Whitespace: There are no trims or whitespace handling in this basic example as you requested. Just ensure that the input accurately matches what is stored in cmdb_ci_service for it to work properly.