In servicenow background script i need to print hello. While query sc_task table with number sctask123 and in sctask we check it request_item.cat_item is Asset allocation then we need to print this
Assistant
In a ServiceNow background script, you can achieve this by querying the sc_task table for the specified task number (sctask123). Then, you'll need to check if the request_item.cat_item is "Asset allocation". If it matches, you'll print "Hello". Below is a script that demonstrates how to do this:
User
I want to write a onload client script on sctask table to check if the request_item.cat_item is asset allocation and short description is 1234 and state is closed complete then make asset field non mandatory
Assistant
User
Can we use current in client script?
Assistant
User
I want script include and client script both. And check if variable sub asset type is desktop then make asset non mandatory
Assistant
javascript
// Create a GlideRecord object for the sc_task table
var taskGR = new GlideRecord('sc_task');
// Set the query to find the task with the number 'sctask123'
taskGR.addQuery('number', 'sctask123');
// Execute the query
taskGR.query();
// Check if a record was found
if (taskGR.next()) {
// Get the request item (REQ#) associated with the task
var requestItemGR = new GlideRecord('sc_req_item');
// Query the sc_req_item table for the request item by its sys_id
requestItemGR.get(taskGR.request_item);
// Check if the cat_item is 'Asset allocation'
if (requestItemGR.cat_item.name == 'Asset allocation') {
// Print 'Hello' if the condition is met
gs.print('Hello');
}
}
Explanation:
GlideRecord for sc_task:
Create a GlideRecord object to query the sc_task table.
Use addQuery to specify the conditions. In this case, it's querying for the task with the number sctask123.
Call query() to execute the query.
Check if a Record Exists:
Use next() to iterate through the results. This example assumes that the number is unique and will only return one result, so you directly work with it.
Retrieve Related sc_req_item:
If a task is found, create another GlideRecord for the sc_req_item table to get the associated request item.
Use get() with the sys_id from the request_item field of sc_task.
Check the cat_item:
Verify if the catalog item name matches "Asset allocation".
If true, use gs.print('Hello') to print "Hello" to the script log output.
Make sure you have necessary permissions for accessing these tables and fields when running this script in your instance. Also, note that accessing fields like request_item.cat_item.name may require the appropriate relationships set up in your instance.
To create an onload client script for the sc_task table that sets the asset field to non-mandatory based on certain conditions, you can follow these steps. The script will check if the request_item.cat_item is "Asset allocation", the short_description is "1234", and the state is "Closed Complete". Here's how you can implement this:
Navigate to your ServiceNow instance and go to System Definition > Client Scripts.
Click on New to create a new client script.
Fill in the form with the following details:
Name: Set Asset Field to Non-Mandatory
Table:sc_task
UI Type: All (if you want this to work in mobile as well)
Type: onLoad
Then, in the Script field, you can paste the following JavaScript code:
javascript
(function executeRule(current, g_form, g_user, g_scratchpad) {
// Get the request item GlideRecord
var reqItemGR = new GlideRecord('sc_req_item');
// Validate that you can retrieve the request item by sys_id
if (reqItemGR.get(current.request_item)) {
// Check if the catalog item name is 'Asset allocation'
if (reqItemGR.cat_item.name == 'Asset allocation') {
// Check the short description and state
if (current.short_description == '1234' && current.state == '3') { // Assuming '3' corresponds to 'Closed Complete'
// Set the 'asset' field to non-mandatory
g_form.setMandatory('asset', false);
}
}
}
})(current, g_form, g_user, g_scratchpad);
Explanation:
Retrieve the request_item: We use a GlideRecord query to load the sc_req_item details using the request_item reference field from the current task record.
Check Conditions: Validate if the cat_item.name is "Asset allocation", the task's short_description is "1234", and the state is "Closed Complete".
Set Non-Mandatory: If all conditions are met, g_form.setMandatory('asset', false) sets the asset field on the form to be non-mandatory.
Important Considerations:
Ensure correct state value: The state comparison in the if statement is based on the state value, often a number. You need to adjust '3' with the accurate state value from your instance which corresponds to "Closed Complete". You can find these values in the dictionary or by inspecting existing records.
Validation and testing: Always test your scripts in a non-production environment to ensure they work as expected and do not cause any unintended behavior on forms.
Security and Performance: Consider the impact of using GlideRecord in a client script, as it queries directly from the server, which can affect performance if not used cautiously. However, it's acceptable here due to the need to check related records not available in the form's current GlideRecord (g_form).
In client scripts, the use of the current object is not supported. The current object, which represents the current record, is available in server-side scripts such as business rules and script includes, but not in client-side scripts like client scripts or UI policies.
However, in client scripts, you have access to the g_form object, which you can use to manipulate form fields, and g_user to access user information. To work with data in client scripts, you typically use g_form methods to get or set field values directly on the form.
Here's how you can adapt the provided logic with a client script:
Script Without current: Instead of using current, use g_form methods.
javascript
(function() {
// Get the request item sys_id from the form
var requestItemId = g_form.getValue('request_item');
if (requestItemId) {
// Call GlideAjax or REST API to get necessary information from the server
var ga = new GlideAjax('CheckCatalogItem'); // Assume this is a Script Include
ga.addParam('sys_id', requestItemId);
ga.getXMLAnswer(function(answer) {
if (answer === 'true') {
var shortDescription = g_form.getValue('short_description');
var state = g_form.getValue('state');
// Check conditions and set the asset field non-mandatory
if (shortDescription === '1234' && state === '3') { // Adjust '3' to your closed complete state value
g_form.setMandatory('asset', false);
}
}
});
}
})();
Explanation:
GlideAjax: If you need information about related records not directly available on the form, you would use a GlideAjax call to execute server-side logic, such as querying the sc_req_item table, and return results to use on the client side.
g_form: Use g_form.getValue('field_name') to retrieve field values present in the current form.
Server Script Include (Example): In the above sample, the GlideAjax call refers to a hypothetical Script Include named CheckCatalogItem. You'd implement server-side logic in this Script Include to perform the check of whether the catalog item name is "Asset allocation" and return that information.
Additional Considerations:
Server Calls: Use GlideAjax sparingly in client scripts for situations where necessary data is not available on the form to prevent performance issues due to excessive server calls.
Testing: Always test the script in a sub-production environment first, ensuring the logic works as expected, especially the state code (like '3'), which you need to confirm for your specific instance.
To achieve this requirement, you'll need to create both a Script Include and a Client Script in ServiceNow. The Script Include will handle server-side logic, specifically fetching required data from the sc_req_item table, while the Client Script will execute on the client side, using GlideAjax to communicate with the Script Include.
Step 1: Create the Script Include
Navigate to System Definition > Script Includes.
Click on New to create a new Script Include.
Here is a basic example of what the Script Include might look like:
javascript
var CheckAssetConditions = Class.create();
CheckAssetConditions.prototype = {
initialize: function() {},
/**
* Method to check conditions on sc_req_item and requested item variables
* @param {String} requestItemId - The sys_id of the Request Item
* @return {Boolean} - True if conditions are met, otherwise false
*/
checkConditions: function(requestItemId) {
var reqItemGR = new GlideRecord('sc_req_item');
if (reqItemGR.get(requestItemId)) {
// Check catalog item and variable conditions here
if (reqItemGR.cat_item.name == 'Asset allocation') {
var variables = new GlideRecord('sc_item_option_mtom');
variables.addQuery('request_item', reqItemGR.sys_id);
variables.addQuery('sc_item_option.variable_name', 'sub_asset_type');
variables.query();
while (variables.next()) {
if (variables.sc_item_option.value == 'desktop') {
return true;
}
}
}
}
return false;
},
type: 'CheckAssetConditions'
};
Step 2: Create the Client Script
Navigate to System Definition > Client Scripts.
Click on New to create a new client script.
Populate the form with appropriate values and use the following script in the Client Script:
javascript
(function() {
// Get the request item sys_id from the form
var requestItemId = g_form.getValue('request_item');
if (requestItemId) {
var ga = new GlideAjax('CheckAssetConditions');
ga.addParam('sysparm_name', 'checkConditions');
ga.addParam('requestItemId', requestItemId);
ga.getXMLAnswer(function(answer) {
if (answer === 'true') {
// Set the 'asset' field to non-mandatory if all conditions are met
g_form.setMandatory('asset', false);
}
});
}
})();
Explanation:
Script Include:
checkConditions Method: This method checks if the cat_item name is "Asset allocation" and if the variable sub_asset_type is set to "desktop". It returns true if both conditions are met.
sc_item_option_mtom Table: This table stores the item options related to a request. The script queries for the "sub_asset_type" variable value.
Client Script:
Uses GlideAjax to call the checkConditions method of the CheckAssetConditions Script Include.
Receives a response from the server and makes the asset field non-mandatory if the server returns true.
Considerations:
Ensure Correct Variable Name: Adjust the variable name 'sub_asset_type' to match the one configured in your instance.
State Values: If you're also dealing with different states, ensure you have logic to handle those as needed.
Testing: Always test both the Script Include and Client Script in a development environment before deploying to production. This ensures the functionality works as expected and doesn’t introduce any performance issues.