In servicenow, i have a catalog that create ritm after submit, and then create tasks in it and a button is visible based on the condition mentioned in script inculde. My requirement is i want to add conditions in script include that this is only visible after count of tasks is more than 2 untill task contains short description 12345 is created and not visible after this task
Assistant
To achieve the desired functionality in ServiceNow, the script include needs to implement logic that checks the number of tasks associated with a Request Item (RITM) and also checks for a specific task with a short description of "12345". This can be implemented using GlideRecord to query the relevant task table and applying your conditions in the script include.
Here's a general approach you can take for your script include:
Retrieve Related Tasks: Use GlideRecord to query the "sc_task" table and retrieve tasks related to your RITM.
Count Tasks: Count the number of tasks associated with the RITM.
Check for Specific Task Description: Loop through the tasks to see if any have the short description "12345".
Determine Visibility: Based on these checks, return true or false to indicate if the button should be visible.
Here's a sample script include that encapsulates this logic:
javascript
var CatalogTaskButtonHelper = Class.create();
CatalogTaskButtonHelper.prototype = {
initialize: function() {},
isButtonVisible: function(ritmSysId) {
if (!ritmSysId) return false;
var taskGR = new GlideRecord('sc_task');
taskGR.addQuery('request_item', ritmSysId);
taskGR.query();
var taskCount = 0;
var taskWithDescriptionExists = false;
while (taskGR.next()) {
taskCount++;
if (taskGR.short_description.toString() === "12345") {
taskWithDescriptionExists = true;
break; // Exit loop if the task with the description is found.
}
}
// Determine button visibility
return taskCount > 2 && !taskWithDescriptionExists;
},
type: 'CatalogTaskButtonHelper'
};
Explanation:
GlideRecord: This object is used to query the sc_task table. The query filters tasks associated with the given ritmSysId.
Task Counting: We count tasks as they are iterated and simultaneously check if a task with the short description "12345" exists.
Visibility Logic: The button is only visible if the number of tasks is greater than 2 and the specific task with short description "12345" has not been created yet.
Usage:
You'd call the isButtonVisible method from the client script or another server-side script where you need to decide on the button's visibility:
javascript
var buttonHelper = new CatalogTaskButtonHelper();
var showButton = buttonHelper.isButtonVisible(current.sys_id);
// Use `showButton` to conditionally display the button.
Ensure that any client script or UI page that calls this script include has proper access to execute server-side code, especially if executed from a UI button, to avoid issues with permissions and security constraints.