Incident management Archives - ServiceNow Guru https://servicenowguru.com/tag/incident-management/ ServiceNow Consulting Scripting Administration Development Tue, 22 Oct 2024 15:56:11 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.2 https://servicenowguru.com/wp-content/uploads/2024/05/cropped-SNGuru-Icon-32x32.png Incident management Archives - ServiceNow Guru https://servicenowguru.com/tag/incident-management/ 32 32 QR Code-Based Incident Creation from URL Parameters https://servicenowguru.com/client-scripts-scripting/qr-code-based-incident-creation-from-url-parameters/ Tue, 22 Oct 2024 15:56:11 +0000 https://servicenowguru.com/?p=17135 Imagine you could report issues with just a quick scan of a QR code. In this article, I'll show you how to set up a system in ServiceNow that lets users scan QR codes to create incident reports. This method makes it easy to report problems with meeting rooms, printers, or any other equipment in your

The post QR Code-Based Incident Creation from URL Parameters appeared first on ServiceNow Guru.

]]>
Imagine you could report issues with just a quick scan of a QR code. In this article, I’ll show you how to set up a system in ServiceNow that lets users scan QR codes to create incident reports. This method makes it easy to report problems with meeting rooms, printers, or any other equipment in your office.

Use Case: Reporting Incidents with QR Codes

Let’s start with the use case. Picture QR codes placed in various locations like meeting rooms, printers, or other office equipment. These QR codes contain URLs with parameters that correspond to the sys_id of the Configuration Item (CI) or asset in the ServiceNow CMDB. When a user scans the QR code, it directs them to an Incident Record Producer with important fields such as LocationAsset Information already filled in. This links the reported issue directly to the correct asset and location, allowing the helpdesk team to quickly identify and resolve the problem, while freeing the user from having to manually enter all the details.

Technical Solution: Catalog Client Script for Parsing URL Parameters

To make this work, we need a catalog client script that reads the URL parameters and maps them to variables with the same name as the “key” in the URL. Here’s the script:

Catalog Client Script

/**
 * Populates catalog variable fields with values from URL parameters.
 * @function
 * @throws {Error} Throws an error if an unexpected situation occurs.
 */
function onLoad() {
    try {
        /** Get the parameters from the URL */
        var _window = window ? window : this.window;
        var urlParams = new URLSearchParams(_window.location.search);

        /** Iterate over each parameter in the URL */
        urlParams.forEach(function(value, key) {
            try {
                /** Check if a variable with the same name exists in the catalog form */
                var variable = g_form.getControl(key);
                if (variable) {
                    /** Set the value in the catalog variable field */
                    g_form.setValue(key, value);
                }
            } catch (innerError) {
                /** Handle errors that occur during iteration */
                console.error('Error during parameter iteration:', innerError);
            }
        });
    } catch (error) {
        /** Handle errors that occur during the main execution */
        console.error('An unexpected error occurred:', error);
        /** You may choose to throw the error again or handle it differently based on your requirements. */
    }
}

How the Script Works

  1. Get the Parameters from the URL: The script starts by checking if the window object is available. It then creates a URLSearchParams object from the URL’s query string, which allows easy access to the URL parameters.
  2. Iterate Over Each Parameter: The script uses the forEach method to iterate over each key-value pair in the URL parameters.
  3. Check for Matching Variables: For each parameter, the script checks if there is a corresponding variable in the catalog form with the same name as the key. It does this using the g_form.getControl(key) method.
  4. Set the Variable Value: If a matching variable is found, the script sets its value to the corresponding value from the URL parameter using the g_form.setValue(key, value) method.
  5. Error Handling: The script includes error handling to catch and log any errors that occur during the main execution or the iteration over parameters. This ensures that any issues are logged for debugging purposes.

Implementation Steps

Here’s how you can set up the QR code solution:

  1. Create a Variable Set: Go to Service Catalog > Catalog Variables > Variable Sets and create a new variable set. Name it something generic and understandable, such as “URLParameterMapper” or “URLVariableBinder,” following your organization’s naming conventions. Add the catalog client script provided above to this variable set.
  2. Generate QR Codes: Create QR codes that encode URLs pointing to the Incident Record Producer. Make sure the URLs include parameters for the CI/asset sys_id.
  3. Create Record Producers or Catalog Items: Set up record producers or catalog items with their own variables or variable sets. Either match the variable names to the keys in the URL parameters, or create the QR code URL so that the keys match the variable names in the record producer. Otherwise, the variables won’t map correctly and won’t populate from the URL.
  4. Add the Variable Set: Add the variable set from step 1 to the record producers or catalog items created in step 3.

Conclusion

By following these steps, users can easily raise incidents by scanning QR codes, with the incident form pre-filled with relevant information from the URL parameters. This streamlines the process of incident creation and ensures accurate reporting of issues related to specific CIs or assets.

The post QR Code-Based Incident Creation from URL Parameters appeared first on ServiceNow Guru.

]]>
Mandatory Knowledge Search Before Ticket Creation https://servicenowguru.com/client-scripts-scripting/mandatory-knowledge-search-ticket-creation/ https://servicenowguru.com/client-scripts-scripting/mandatory-knowledge-search-ticket-creation/#comments Mon, 14 May 2012 12:37:38 +0000 https://servicenowguru.wpengine.com/?p=4399 Greetings from Knowledge12 in New Orleans! I’ll be here all week with CrossFuze Solutions so if you’re here and see me, please introduce yourself. I’m looking forward to putting a face to all of the names of people I’ve worked with remotely. I’m working with a client currently who wants to encourage the use of

The post Mandatory Knowledge Search Before Ticket Creation appeared first on ServiceNow Guru.

]]>
Greetings from Knowledge12 in New Orleans! I’ll be here all week with CrossFuze Solutions so if you’re here and see me, please introduce yourself. I’m looking forward to putting a face to all of the names of people I’ve worked with remotely.

I’m working with a client currently who wants to encourage the use of their Knowledge Base to reduce their ticket load. This, of course, is a common requirement but it’s one that I don’t think is adequately addressed in ServiceNow currently. In this post I’ll share my implementation of their idea. I don’t think it’s a perfect solution, but it might give you some ideas to improve your own process and design. This post shows how you can force a KB search using the standard search dialog whenever a user creates an incident. I’ve designed the solution to work in a standard incident form and within the service catalog so that it can be applied in whatever way you create tickets in your environment.
Automatic KB Popup

When I designed this solution, my main concern was to implement a solution that would promote the Knowledge Base search without being completely annoying to the end user. Because of this, I wanted to be very careful about allowing specific control over the event trigger that produces the KB popup window. I also wanted the solution to use as much of the out-of-box behavior as possible.

The solution I decided on was to use a client script to add a ‘blur’ event to the ‘Short Description’ field. The ‘blur’ event for a field runs when the field loses focus. In the case of the ‘Short Description’ field, it runs when somebody clicks into the field, and then clicks somewhere else. I also wanted the script to only run for a new record and only to run when there was an actual value in ‘Short Description’.

From a Standard Form Field

This script can be pasted directly into any ‘onLoad’ client script on a standard form field. The only requirements are that the form includes a field named ‘short_description’ and that field uses the standard KB search icon.

‘Pop KB Search from Short Description’
Name: Pop KB Search from Short Description
Table: Incident
Type: onLoad
Script:

function onLoad() {
//Set the maximum number of times the popup will appear
var maxKBPop = 1;
var kbPopCount = 0;//Only run for new records
if(g_form.isNewRecord()){
//Add an 'onBlur' event to search KB from 'short_description' field
var field = g_form.getControl('short_description');
Event.observe(field, 'blur', function() {
//Only search if there is a value
if(g_form.getValue('short_description') != ''){
//Only pop the search one time
if(kbPopCount < maxKBPop){
kbPopCount++;
customKBPopup(field.id);
}
}
});
}
}
function customKBPopup(me) {
self.fillField = me;
var shortElement = gel(me);
var searchText = shortElement.value;
var url = 'kb_find.do?sysparm_search=' + encodeURI(searchText);
url += "&sysparm_nameofstack=kbpop";
url += "&sysparm_kb_search_table=" + g_form.getTableName();
url += "&sysparm_operator=IR_AND_OR_QUERY";
popupOpenStandard(url, 'kb2task');
}

From a Service Catalog Variable

You can also force a KB search with a catalog variable (on a record producer or catalog item). The script below assumes that you’ve got a string field named ‘short_description’. Because the knowledge icon doesn’t exist for service catalog variables, the script manufactures the icon and link on the fly so that it behaves just like the standard field.

‘Pop KB Search from Short Description’
Name: Pop KB Search from Short Description
Type: onLoad
Script:

//Add an event handler to pop KB Search when focus moves from Short Description field
function onLoad() {
//Set the maximum number of times the popup will appear
var maxKBPop = 1;
var kbPopCount = 0;
var field = g_form.getControl('short_description');
//Add the KB Search icon
$(field.id).up(1).insert('<a><img class="knowledge" title="Search Knowledge" src="images/icons/knowledge.gifx" width="16" height="16" border="0" /></a></td');
$('status.' + field.id).up('td').setAttribute('colSpan', '3');//Add an 'onBlur' event to search KB from 'short_description' field
Event.observe(field, 'blur', function() {
//Only search if there is a value
if(g_form.getValue('short_description') != ''){
//Only pop the search one time
if(kbPopCount < maxKBPop){
kbPopCount++;
kbPopupSC();
}
}
});
}function kbPopupSC() {
var shortElement = $(g_form.getControl('short_description').id);
var searchText = shortElement.value;
var url = 'kb_find.do?sysparm_search=' + encodeURIComponent(searchText);
url += "&sysparm_operator=IR_AND_OR_QUERY";

popupOpenStandard(url, "kb2task");
}

The post Mandatory Knowledge Search Before Ticket Creation appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/mandatory-knowledge-search-ticket-creation/feed/ 26
Building a CI Change Calendar Macro – On The Fly https://servicenowguru.com/reporting/ci-change-calendar-macro/ https://servicenowguru.com/reporting/ci-change-calendar-macro/#comments Wed, 20 Jul 2011 12:39:19 +0000 https://servicenowguru.wpengine.com/?p=3920 A co-worker asked me for some help yesterday fulfilling an interesting requirement. He needed to set up a configuration item reference field or catalog variable that would display a calendar macro that, when clicked, would open a popup window containing a change calendar report for that configuration item. I figured this idea might be of

The post Building a CI Change Calendar Macro – On The Fly appeared first on ServiceNow Guru.

]]>
A co-worker asked me for some help yesterday fulfilling an interesting requirement. He needed to set up a configuration item reference field or catalog variable that would display a calendar macro that, when clicked, would open a popup window containing a change calendar report for that configuration item. I figured this idea might be of use to others so I’m posting it here!

CI Change Calendar Report Macro Popup

I’ve written before about UI macros, and different types of popups on SNGuru. I’ve also written about how your change management process can be a valuable input into your other ITIL processes such as incident management. You can refer to those posts if you’re interested in more detail on some of the ideas used in this article.

The real magic of this solution is how you can create this calendar report ‘on-the fly’ simply by constructing the correct URL. This is something that a colleague of mine, Bobby Edmonds, tipped me off to a couple of years ago. The URL contains several ‘sysparm_’ parameters that point to the fields on the report form. Once you know those, you just have to pass them the correct values. The URL for the calendar report needs to look something like this…

sys_report_template.do?sysparm_table=change_request&sysparm_type=calendar&sysparm_cal_field=end_date&sysparm_from_list=true&sysparm_manual_labor=true&sysparm_query=^end_date%3Ejavascript:gs.endOfLastMonth()'^cmdb_ci=YOUR_CI_SYS_ID_HERE
I plan on writing a post about creating on-the-fly reports soon, but you can piece together the necessary URL parameters for a report by poking around any existing report in your system with a DOM inspector to see what parameters are necessary.

You might be asking, “Why don’t you just point directly to the existing change calendar report URL?”. You could certainly do that, and avoid all of the above, but the requirement in this case is to have the calendar report filtered based on the CI chosen in the field, so it needs to be dynamic.

Because this URL will be initiated from a UI macro (for this example) we’ll need to escape the ampersands and you can see that I’ve done that in the code below. The rest of the code is almost identical to the out-of-box ‘user_show_incidents’ UI macro that you see on the incident ‘Caller’ field. Once the URL is constructed we can use ‘popupOpen’ to display the report in a popup!

Your UI macro should look like this. Once set up, it can be added to the CI reference field of your choice by adding the ‘ref_contributions=ci_show_change_calendar’ attribute to the dictionary entry ‘Attributes’ field of that CI reference field.

‘ci_show_change_calendar’ UI macro
Name: ci_show_change_calendar
Description:
Show CI change calendar popup link
Activate by:
– set the active field in this macro to true
– adding the attribute to a dictionary field: ref_contributions=ci_show_change_calendar
Script:

<!--?xml version="1.0" encoding="utf-8" ?-->



<script>
function showCIChangeCalendar(reference) {
   //Construct the calendar report URL
   var url = 'sys_report_template.do?sysparm_table=change_request$[AMP]sysparm_type=calendar$[AMP]sysparm_cal_field=end_date$[AMP]sysparm_from_list=true$[AMP]sysparm_manual_labor=true$[AMP]sysparm_query=^end_date%3Ejavascript:gs.endOfLastMonth()^cmdb_ci=';
   
   var s = reference.split('.');
   var referenceField = s[1];
   var v = g_form.getValue(referenceField);
   url = url + v;
   //Open the popup 
   var features = "width=700,height=650,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollbars=1";
   popupOpen(url, 'show_calendar', 700, 650, features, true);
}
</script>

 

Add a Change Calendar Macro to a Catalog Reference Variable

You can use a similar technique to add a calendar macro icon next to a catalog reference variable. The big, additional challenge in the service catalog is that reference field macros are not supported for catalog variables. In order to add one you have two options. The first would be to create a UI page or UI macro-type variable similar to the example above. The big drawback would be that the icon wouldn’t appear right next to the reference variable without some clever client scripting.
The second option (which I chose) is to use a catalog client script to construct the macro on-the-fly and place it in the correct spot next to the reference field. This technique is based on a previous solution I wrote about in another SNCGuru article about placing macros next to non-reference fields.

Your catalog client script should look like this. Just add the name of your CI reference variable in the ‘ciVarName’ line below.

‘Add CI Change Calendar Macro’ Catalog Client Script
Name: Add CI Change Calendar Macro
Applies to: Catalog item or variable set of your choice
Type: onLoad
Script (Pre-Fuji version):

function onLoad() {
//The reference variable name to put the icon next to
var ciVarName = 'cmdb_ci';//Add the icon decoration to the reference field
var ciEl = 'lookup.' + g_form.getControl(ciVarName).id;
$(ciEl).insert({
after: '<a id="cmdb_ci_calendar_macro" style="padding-right: 4px;"></a><img title="CI Change Calendar" src="images/icons/dayview.gifx" alt="CI Change Calendar" />'
});
//Add the 'onclick' event
$('cmdb_ci_calendar_macro').observe('click', showCIChangeCalendar);

function showCIChangeCalendar(){
//Construct the calendar report URL
var url = 'sys_report_template.do?sysparm_table=change_request&sysparm_type=calendar&sysparm_cal_field=end_date&sysparm_from_list=true&sysparm_manual_labor=true&sysparm_query=^end_date%3Ejavascript:gs.endOfLastMonth()';
if(g_form.getValue(ciVarName) != ''){
url = url + '^cmdb_ci=' + g_form.getValue(ciVarName);
}

//Open the popup
var features = "width=700,height=650,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollbars=1";
popupOpen(url, 'show_calendar', 700, 650, features, true);
}
}

Script (Fuji version):

function onLoad() {
//The reference variable name to put the icon next to
var ciVarName = 'cmdb_ci';

//Add the icon decoration to the reference field
var ciEl = 'lookup.' + g_form.getControl(ciVarName).id;
$(ciEl).insert({
after: '<a id="cmdb_ci_calendar_macro" class="icon-calendar btn btn-default sn-tooltip-basic" style="padding: 6px 10px; vertical-align: text-bottom;" title="" data-original-title="CI Change Calendar"></a>'
});
//Add the 'onclick' event
$('cmdb_ci_calendar_macro').observe('click', showCIChangeCalendar);

function showCIChangeCalendar(){
//Construct the calendar report URL
var url = 'sys_report_template.do?sysparm_table=change_request&sysparm_type=calendar&sysparm_cal_field=end_date&sysparm_from_list=true&sysparm_manual_labor=true&sysparm_query=^end_date%3Ejavascript:gs.endOfLastMonth()';
if(g_form.getValue(ciVarName) != ''){
url = url + '^cmdb_ci=' + g_form.getValue(ciVarName);
}

//Open the popup
var features = "width=700,height=650,toolbar=no,status=no,directories=no,menubar=no,resizable=yes,scrollbars=1";
popupOpen(url, 'show_calendar', 700, 650, features, true);
}
}

When you’re done, your catalog variable will have a calendar link next to it that looks like this…
CI Change Calendar Macro Catalog Variable

The post Building a CI Change Calendar Macro – On The Fly appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/reporting/ci-change-calendar-macro/feed/ 5
Track Affected CIs in One Place https://servicenowguru.com/cmdb/track-affected-cis-one-place/ https://servicenowguru.com/cmdb/track-affected-cis-one-place/#comments Fri, 27 May 2011 12:47:53 +0000 https://servicenowguru.wpengine.com/?p=3740 It should come as no surprise to you that, if used properly, your CMDB can be an extremely valuable input to your incident/problem/change processes. This is true not only of the actual CIs, but also the ‘Affected CI’ records that you create. ServiceNow gives you a couple of different places to track this information. The

The post Track Affected CIs in One Place appeared first on ServiceNow Guru.

]]>
It should come as no surprise to you that, if used properly, your CMDB can be an extremely valuable input to your incident/problem/change processes. This is true not only of the actual CIs, but also the ‘Affected CI’ records that you create. ServiceNow gives you a couple of different places to track this information. The first is the ‘Configuration Item’ field available to all Task types in the system. You can add this field by personalizing the form for any task. The second is the ‘Affected CIs’ (task_ci) many-to-many table. This can be added to any task form in your system by personalizing the related lists for that form.

This setup allows you to track a primary CI or Business Service against a given task in the field on the form, and it also allows you to track multiple Affected CIs against a task if necessary in the related list. What I don’t like about this setup is that these are managed independently so there’s not a single place to see ALL of the Affected CIs in your environment. My solution to this problem has always been to centralize all of this information into the ‘Affected CIs’ related list by copying the ‘Configuration Item’ field value into it. This simple idea gives you a much better look into your Affected CIs for reporting, and allows for more proactive troubleshooting through CI Business Service Maps as an input into your task processes.

This customization is pretty simple and can be accomplished through the application of two business rules. The first business rule sits on the ‘Task’ table and should be configured as follows…

‘Sync CI with Affected CIs’ Business Rule
Name: Sync CI with Affected CIs
Table: Task
When: After
Insert: True
Update: True
Condition: current.cmdb_ci.changes()
Script:

if(previous.cmdb_ci){
   removeCI();
}
if(current.cmdb_ci){
   addCI();
}

function removeCI(){
   //Get Affected CI records for this task and delete the CI if necessary
   var rec = new GlideRecord('task_ci');
   rec.addQuery('task', current.sys_id);
   rec.addQuery('ci_item', previous.cmdb_ci);
   rec.query();
   while(rec.next()){
      //Delete the Affected CI record
      rec.deleteRecord();
   }
}

function addCI(){
   //Get Affected CI records for this task and add the CI if necessary
   var rec = new GlideRecord('task_ci');
   rec.addQuery('task', current.sys_id);
   rec.addQuery('ci_item', current.cmdb_ci);
   rec.query();
   if(!rec.next()){
      //Create a new Affected CI record
      var ci = new GlideRecord('task_ci');
      ci.initialize();
      ci.task = current.sys_id;
      ci.ci_item = current.cmdb_ci;
      ci.insert();
   }
}

The second business rule sits on the ‘CIs Affected’ (task_ci) table and should be configured as follows…

‘Prevent removal/update of primary CI’ Business Rule
Name: Prevent removal/update of primary CI
Table: CIs Affected (task_ci)
When: Before
Update: True
Delete: True
Script:

//Check the parent task to make sure that the CI is not listed there
if(current.ci_item && current.operation() == 'delete' && current.ci_item == current.task.cmdb_ci){
   //Disallow removal
   gs.addInfoMessage('You cannot remove this CI since it is the primary CI on the associated task.</br>Please change or remove the CI from the task form.');
   current.setAbortAction(true);
}
if(current.ci_item.changes() && current.operation() == 'update' && previous.ci_item == current.task.cmdb_ci){
   //Disallow modification
   gs.addInfoMessage('You cannot change this CI since it is the primary CI on the associated task.</br>Please change or remove the CI from the task form.');
   current.setAbortAction(true);
}

Harnessing the power of the CIs Affected (task_ci) table

Once this is done, any change to the ‘Configuration Item’ field on a task record will automatically result in the creation of an ‘Affected CIs’ entry for that same CI. Now you can set up all of your reports for this area against this table. One of the most powerful things you can do with this data is to set up a BSM Map Action icon that can be displayed to show people from within a BSM map which CIs are being affected by different tasks in the system. There’s a great example on the ServiceNow Wiki that shows you how you can do this.

Affected CIs BSM Map Actions

The post Track Affected CIs in One Place appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/cmdb/track-affected-cis-one-place/feed/ 7
Advanced Incident Management https://servicenowguru.com/service-now-general-knowledge/advanced-incident-management/ https://servicenowguru.com/service-now-general-knowledge/advanced-incident-management/#comments Thu, 26 May 2011 12:35:51 +0000 https://servicenowguru.wpengine.com/?p=3719 I had a great time presenting on Advanced Incident Management last week at Knowledge11. During that session I demonstrated a lot of very useful functionality that I’ve used and created to improve the standard incident management setup for technicians working in ServiceNow. Since most of my presentation was a demo, I promised the attendees that

The post Advanced Incident Management appeared first on ServiceNow Guru.

]]>
I had a great time presenting on Advanced Incident Management last week at Knowledge11. During that session I demonstrated a lot of very useful functionality that I’ve used and created to improve the standard incident management setup for technicians working in ServiceNow. Since most of my presentation was a demo, I promised the attendees that I would post information about the solutions we talked about there. Read on if you want to see some great ideas to improve incident management in your organization!

Incident Form

I know some of this is a pretty rough draft. If you’re interested in more detail on any of these topics, please comment below and I’ll write a post to address it.
If you’re interested in seeing the slides from this presentation (or any other session at Knowledge11) you can access them through the ServiceNow community site. Here’s a link!

Overall Goals:

  • Keep it simple!
  • Leverage existing data
  • Smart & intuitive design
  • Get out of the code
  • Automate and simplify repeated tasks

…all with the purpose of speeding time to resolution and improving customer satisfaction!

-Keep it simple!

-Advanced != Complex. Don’t overload your incident form with low-use garbage!
-Base incident form (screenshot above). All information is relevant and useful

-Leverage existing data

-CMDB
Consolidate your ‘Configuration item’ field and ‘Affected CIs’ lists to get a better picture of what’s actually being impacted in your environment.
-Configuration item field macro icons
-BSM Map: relationships, map action icon showing only CI field tasks
Use of ‘Affected CIs’ list with BSM map action icons
-Change calendar (FSC): Don’t forget that change information can be a valuable input into incident resolution.
On-call schedule popup
Custom knowledge search

-Get out of the code

-Lookup tables are a great way to separate code from data and keep yourself out of the code where possible
Priority lookup
Assignment lookup

-Smart & intuitive design

Priority 1 incident scroller
Outlook-style module counts
-Color change on comments field (Field styles)
Simultaneous task update alert
Create user without leaving the form
Knowledge search from homepage

-Automate & simplify repeated tasks & actions

-Templates (Advanced Templates)
Suggestion fields
QuickForm from list

The post Advanced Incident Management appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/service-now-general-knowledge/advanced-incident-management/feed/ 6
On-call Schedule Popup UI Macro https://servicenowguru.com/ui-macros/on-call-calendar-popup-ui-macro/ https://servicenowguru.com/ui-macros/on-call-calendar-popup-ui-macro/#comments Mon, 09 May 2011 16:24:29 +0000 https://servicenowguru.wpengine.com/?p=3623 Here’s a UI macro that I’ve used for a couple of clients that allows you to pop open an on-call rotation schedule for the group selected in any ‘Group’ reference field in the system. This will probably be most useful for the ‘Assignment group’ table that you use on the task table. As with any

The post On-call Schedule Popup UI Macro appeared first on ServiceNow Guru.

]]>
Here’s a UI macro that I’ve used for a couple of clients that allows you to pop open an on-call rotation schedule for the group selected in any ‘Group’ reference field in the system. This will probably be most useful for the ‘Assignment group’ table that you use on the task table. As with any reference field UI macro, you can add the UI macro to your reference field by adding the ‘ref_contributions’ attribute to the dictionary entry of your reference field. So this macro would require the ‘ref_contributions=show_group_on_call_schedule’ attribute. Since it displays on-call information, it is also dependent on the ‘on_call scheduling’ plugin being installed.

SNOnCallSchedule

Here’s the code you’ll need for your UI macro. This code should work without modification for any group reference field in your system.

‘show_group_on_call_schedule’ UI Macro
Name: show_group_on_call_schedule
Description: Displays an on-call schedule for the selected assignment group.
Requires ‘ref_contributions=show_group_on_call_schedule’ dictionary attribute.
XML:

<!--?xml version="1.0" encoding="utf-8" ?-->



<span id="${jvar_n}" class="btn btn-default icon-date-time" tabindex="0" title="${gs.getMessage('Show group on-call schedule')}">
<span class="sr-only">${gs.getMessage('Show group on-call schedule')}</span>
</span><script>
function showOnCallSchedule(reference){
   //Get the current group
   var group = g_form.getValue(reference.split('.')[1]);
   //Query to see if an on-Call rotation exists
   var grpRota = new GlideRecord('cmn_rota');
   grpRota.addQuery('group', group);
   grpRota.addQuery('active', true);
   grpRota.query();
   if(grpRota.hasNext()){
      //Construct a URL for the popup window
      var url = 'show_schedule.do?sysparm_type=roster$[AMP]sysparm_zoom=weekly$[AMP]sysparm_group_id=' + group;
      //Open the popup
      popupOpenStandard(url);
   }
   else{
      alert('No active rotation specified for the selected group.');
   }
}
</script>

The post On-call Schedule Popup UI Macro appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/ui-macros/on-call-calendar-popup-ui-macro/feed/ 21
Pause or Toggle a Time Worked Field Timer https://servicenowguru.com/system-ui/pausetoggle-time-worked-field/ https://servicenowguru.com/system-ui/pausetoggle-time-worked-field/#comments Tue, 22 Feb 2011 14:57:29 +0000 https://servicenowguru.wpengine.com/?p=3384 There are several ways to do time tracking in ServiceNow. One of the ways used frequently (especially in Incident Management) is the ‘Time Worked’ field. The ServiceNow wiki describes this functionality. I often see the requirement to have some control over the stop/start of this Time Worked field for customers using this functionality. This

The post Pause or Toggle a Time Worked Field Timer appeared first on ServiceNow Guru.

]]>

There are several ways to do time tracking in ServiceNow. One of the ways used frequently (especially in Incident Management) is the ‘Time Worked’ field. The ServiceNow wiki describes this functionality. I often see the requirement to have some control over the stop/start of this Time Worked field for customers using this functionality. This post describes the approaches I’ve used in the past to meet this need.

Paused Time Worked Timer

Default Start/Stop state for Time Worked field for ALL Tasks

ServiceNow includes a simple property that allows you to specify whether the time worked timer should be started or paused when a task form loads. This property might meet the needs of some customers, but lacks the needed flexibility for most people using the time worked field. The property name is ‘glide.ui.timer.started’ and can be accessed under the ‘UI Properties’ module as shown here…
Pause Timer Property

Toggle Time Worked Client Script

If you need the additional flexibility of starting or stopping the time worked field for particular task types or even for particular states in given task types, you need to use a client script to start and stop the timer. One common requirement I’ve seen for this is to have the timer always be stopped if the form loads for an already-closed or resolved incident ticket. For this scenario, you could use the script I’ve created below. The script I’ve written takes 2 parameters…the first takes the name of the timer field you want to start or stop, and the second parameter (which is optional) allows you to set the timer to a specific time if needed.

function onLoad() {
	if(g_form.getElement('time_worked')){
		toggleTimer('time_worked','00:00:00');
	}
}

function toggleTimer(fieldName,timerVal){
	try{
		//Get the necessary timer elements for fieldName given
		var timerEl = $('element.' + g_form.tableName + '.' + fieldName);
		var timerIcon = $('link.' + g_form.tableName + '.' + fieldName);
		if (timerEl != null){
			//Make sure script does not break if field not present
			var timerPause = timerEl.select('input[id*=paused]')[0];
			
			//Toggle the timer
			if(timerPause.value == 'false'){
				timerPause.value = 'true';
				timerIcon = $('link.' + g_form.tableName + '.' + fieldName);
				timerIcon.removeClassName('icon-stop');
				timerIcon.addClassName('icon-play');
			}
			else{
				timerPause.value = 'false';
				timerIcon.removeClassName('icon-play');
				timerIcon.addClassName('icon-stop');
			}
			//Reset the timer to timerVal given
			if(timerVal){
				g_form.setValue(fieldName,timerVal);
			}
		}
	}catch(e){}
}

The post Pause or Toggle a Time Worked Field Timer appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/system-ui/pausetoggle-time-worked-field/feed/ 33
Calendar or Schedule-based Incident Autoclose https://servicenowguru.com/business-rules-scripting/calendar-based-incident-autoclose/ https://servicenowguru.com/business-rules-scripting/calendar-based-incident-autoclose/#comments Mon, 24 Jan 2011 16:43:03 +0000 https://servicenowguru.wpengine.com/?p=2097 Service-now provides the ability to automatically move incidents marked as ‘Resolved’ into a ‘Closed’ state after a certain number of days. In my experience I’ve found that this type of resolution/closure workflow is really the best way to configure your incident management setup because it allows end-users the ability to reopen incidents within a certain

The post Calendar or Schedule-based Incident Autoclose appeared first on ServiceNow Guru.

]]>
Service-now provides the ability to automatically move incidents marked as ‘Resolved’ into a ‘Closed’ state after a certain number of days. In my experience I’ve found that this type of resolution/closure workflow is really the best way to configure your incident management setup because it allows end-users the ability to reopen incidents within a certain window (while they’re still marked as ‘Resolved’) but it also ensures that eventually all of the incident tickets move to a ‘Closed’ state where they won’t be reopened so that you can accurately calculate SLAs and reporting metrics.

The key piece to this auto close functionality is the ‘incident autoclose’ business rule on the ‘Incident’ table. It works in conjunction with the property shown here – that sets the number of days after which a resolved incident will be moved to a closed state. The ‘incident autoclose’ script works great but it is based off of a basic date calculation that doesn’t take into account any business hours or holidays. Shown below are some modified versions of the ‘incident autoclose’ script that take into account the default system calendar (in the case of calendar-based autoclose), or your choice of any system schedule set up in your system (in the case of schedule-based autoclose).

Calendar-based Incident Autoclose Script

NOTE: Calendars have been replaced in favor of schedules in Service-now. This calendar-based script is provided simply for reference purposes for those who may be using this script already. I would advise you to use the schedule-based script below if at all possible because it allows you to specify a specific schedule for the calculation (giving you much more flexibility and control) rather than simply using the default system calendar.
// This script automatically closes incidents that are resolved
// and haven't been updated in a chosen number of days. You
// can set this number as a property in System Properties.
// If you want a comment placed in the incident, uncomment the
// 'gr.comments' line below.

var ps = gs.getProperty('glide.ui.autoclose.time');
var pn = parseInt(ps);

if (pn > 0) {
   var gr = new GlideRecord('incident');
   gr.addQuery('state', 6);
   gr.query();
   while(gr.next()){
      //Close any records that have not been updated in 'pn' number of days
      //Date difference calculated based on default system calendar
      var dif = gs.calDateDiff(gs.nowDateTime(), gr.sys_updated_on, true);
      if(dif >= pn*86400){
         gr.state = 7;
         //gr.comments = 'Incident automatically closed after ' + pn + ' days in the Resolved state.';
         gr.active = false;
         gr.update();
      }
   }
}

Schedule-based Incident Autoclose Script

This schedule-based script is the BEST solution if you are setting up any kind of autoclose functionality in your system. The use of schedules gives you much more flexibility to determine exactly how much time should pass before closing out a resolved ticket. Schedules can be managed by navigating to ‘System Scheduler->Schedules’ in the left navigation pane of your Service-now instance. One important thing to note is that ‘Number of days’ is actually the number of 24 hour periods!
// This script automatically closes incidents that are resolved
// and haven't been updated in a chosen number of days. You
// can set this number as a property in System Properties.
// If you want a comment placed in the incident, uncomment the
// 'gr.comments' line below.

var ps = gs.getProperty('glide.ui.autoclose.time');
var pn = parseInt(ps);

if(pn > 0){
   //Get a schedule by name to calculate duration
   var schedRec = new GlideRecord('cmn_schedule');
   schedRec.get('name', '8-5 weekdays');
   if (typeof GlideSchedule != 'undefined')
      var sched = new GlideSchedule(schedRec.sys_id);
   else
      var sched = new Packages.com.glide.schedules.Schedule(schedRec.sys_id);

   //Get the current date/time in correct format for duration calculation
   var actualDateTime = new GlideDateTime();
   actualDateTime.setDisplayValue(gs.nowDateTime());

   //Query for resolved incident records
   var gr = new GlideRecord('incident');
   gr.addQuery('state', 6);
   gr.query();
   while(gr.next()){
      //Close any records that have not been updated in 'pn' number of days
      //Date difference calculated based on specified schedule
      var dif = sched.duration(gr.sys_updated_on.getGlideObject(), actualDateTime).getDayPart();
      if(dif >= pn){
         gr.state = 7;
         gr.active = false;
         //gr.comments = 'Incident automatically closed after ' + pn + ' days in the Resolved state.';
         gr.update();
      }
   }
}

Schedule-based Incident Autoclose Script (BY HOURS!)

The fact that ‘Number of days’ is actually the number of 24 hour periods ends up being pretty confusing for people sometimes. As I’ve dealt with this issue several times now, I think the best way to do incident autoclose based on a schedule is to do the autoclose on an hourly basis. This eliminates the ‘Number of days’ confusion and it also gives you the added benefit of a bit more granularity. If you use this script, you should also make sure to change the ‘glide.ui.autoclose.time’ property description to hours instead of days.
// This script automatically closes incidents that are resolved
// and haven't been updated in a chosen number of hours. You
// can set this number as a property in System Properties.
// If you want a comment placed in the incident, uncomment the
// 'gr.comments' line below.

var ps = gs.getProperty('glide.ui.autoclose.time');
var pn = parseInt(ps);

if(pn > 0){
   //Get a schedule by name to calculate duration
   var schedRec = new GlideRecord('cmn_schedule');
   schedRec.get('name', '8-5 weekdays excluding holidays');
   if (typeof GlideSchedule != 'undefined')
      var sched = new GlideSchedule(schedRec.sys_id);
   else
      var sched = new Packages.com.glide.schedules.Schedule(schedRec.sys_id);
   
   //Get the current date/time in correct format for duration calculation
   var actualDateTime = new GlideDateTime();
   actualDateTime.setDisplayValue(gs.nowDateTime());
   
   //Query for resolved incident records
   var gr = new GlideRecord('incident');
   gr.addQuery('state', 6);
   gr.query();
   while(gr.next()){
      //Close any records that have not been updated in 'pn' number of hours
      //Date difference calculated based on specified schedule
      var difDay = sched.duration(gr.sys_updated_on.getGlideObject(), actualDateTime).getDayPart()*24;
      var difHour = sched.duration(gr.sys_updated_on.getGlideObject(), actualDateTime).getDurationValue().split(':')[0].substr(-2);
      var dif = difDay + parseInt(difHour.replace(/^[0]+/g,""));
     
      if(dif >= pn){
         gr.state = 7;
         gr.active = false;
         //gr.comments = 'Incident automatically closed after ' + pn + ' hours in the Resolved state.';
         gr.update();
      }
   }
}

The post Calendar or Schedule-based Incident Autoclose appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/business-rules-scripting/calendar-based-incident-autoclose/feed/ 27
Creating a Many-to-Many relationship in ServiceNow https://servicenowguru.com/relationships/creating-manytomany-relationship-servicenowcom/ https://servicenowguru.com/relationships/creating-manytomany-relationship-servicenowcom/#comments Fri, 22 Jan 2010 20:09:05 +0000 https://servicenowguru.wpengine.com/?p=682 Service-now allows you to easily create relationships between tables without having to know a whole lot about the underlying table structure. If you’ve ever worked with a reference field then you’ve worked with one of these relationships. A reference field is simply a one-to-many relationship between 2 tables in ServiceNow. The ‘one’ end of the

The post Creating a Many-to-Many relationship in ServiceNow appeared first on ServiceNow Guru.

]]>
Service-now allows you to easily create relationships between tables without having to know a whole lot about the underlying table structure. If you’ve ever worked with a reference field then you’ve worked with one of these relationships. A reference field is simply a one-to-many relationship between 2 tables in ServiceNow. The ‘one’ end of the relationship is displayed as a reference field on the form. The ‘many’ end of the relationship is displayed on the referenced table as a related list.
In some cases, it may also be necessary to create a many-to-many relationship in your instance. Because ServiceNow ships with most of these relationships already defined, it’s rare that you’ll have to create one. If you do have to create a many-to-many relationship, here’s how you could do it.

For this example, we’ll assume that we need a many-to-many relationship between the Incident and the Change request tables. One Incident can be related to many changes (maybe several changes are required as a result of an incident) and one Change request can be related to many Incidents (implementation of a change results in many incidents).

1) Navigate to the m2m table
There are two tables in your ServiceNow instance that contain many-to-many relationship information. The first one (sys_collection) contains the out-of-box relationships and should be used only for reference purposes. The second one (sys_m2m) is where you’ll want to create your own many-to-many definitions. It’s probably a good idea to create your own modules to link to these tables so that you can easily access them if you’re going to be dealing with m2m tables very often. In most cases these tables won’t be used very much so it may be easier just to navigate to them directly in the application filter in your left navigation or by navigating directly by url. The easiest way is just to type ‘sys_m2m.list’ in your left navigation filter.

 

2) Create a new Many-to-Many relationship tableClick the ‘New’ button on the ‘sys_m2m’ table list and create a new record. There are really only 2 fields that you need to fill in since the rest gets automatically calculated for you. All you need to specify are the ‘From table’ and the ‘To table’ values. For this example we’ll specify ‘Incident’ as our ‘from table’ and ‘Change request’ as our ‘to table’. These values could be interchanged with no impact on the end result. You do want to pay attention to the values in the other fields though since they indicate what your table will be named along with how your related lists will be labeled. Although these are all calculated automatically, you can change them if needed.

 

3) Add the related list to your Change request table

Navigate to your Change request form, right-click the form header, and personalize the related lists for the form. Select the ‘Incidents’ list to add to your form. All One-to-Many lists have a ‘->’ separating the relationship. Many-to-Many lists (and custom formatters) have no separator.

 

4) Add the related list to your Incident tableFollow the same procedure for your Incident table. This list should show up as ‘Change requests’, but may show up with the name of your many-to-many table as shown below. If your related list doesn’t show up correctly, submit an incident to ServiceNow support.

 

5) Relate a record to test it outYour related lists will show up at the bottom of each form. Once you have added the related lists to both sides of the relationship, it is easy to relate records to each other using the ‘New’ and ‘Edit’ buttons on the related list.

The post Creating a Many-to-Many relationship in ServiceNow appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/relationships/creating-manytomany-relationship-servicenowcom/feed/ 14
One Field Shared Between Many Tables https://servicenowguru.com/scripting/one-field-shared-between-many-tables/ https://servicenowguru.com/scripting/one-field-shared-between-many-tables/#comments Fri, 01 Jan 2010 00:06:58 +0000 https://servicenowguru.wpengine.com/?p=594 One common problem I encounter with Service-now deployments has to do with the sharing of a field between many tables extended off of the same parent table. Because the Task table and the Configuration Item table make heavy use of extended tables this is where I see the problem most often. What is the best way to make changes to a shared field for the table that I'm working on, but not impact other tables that may be using the same field?

The post One Field Shared Between Many Tables appeared first on ServiceNow Guru.

]]>
One common problem I encounter with ServiceNow deployments has to do with the sharing of a field between many tables extended off of the same parent table. Because the Task table and the Configuration Item table make heavy use of extended tables this is where I see the problem most often. What is the best way to make changes to a shared field for the table that I’m working on, but not impact other tables that may be using the same field?

Let’s say that I’m in the middle of a Change management deployment and I’m using the ‘Configuration item’ field on my Change form. At the same time, my company is trying to roll out Incident management so there’s also someone from another department trying to make configuration changes to the ‘Configuration item’ field on the Incident form. The Incident management process says that the Configuration item field is optional while Change management says that it should be mandatory. Incident management has a very complex reference qualifier for the field, but Change management doesn’t want a reference qualifier at all. Since there is only one dictionary entry for the Configuration item field, we can’t both have our way if we are making configuration changes on the dictionary entry. Below are a few of the common scenarios where you might see this problem and how you can make it work for all tables that access the shared field.

If there’s a central theme to all of these scenarios it is that you need to pay very close attention to what you’re doing when you personalize the dictionary, label, or choices for any field on an extended table. Chances are that the field you’re personalizing is shared between other tables and you’ll end up impacting another area of the application. Hopefully if you do it’s intentional :).

1- Mandatory fields:

Although there is a checkbox on the dictionary table to make a field mandatory, it should be used ONLY when the field in question should always be mandatory in every situation for every table that uses the field. As this is very rarely the case, it’s usually much more effective just to make the decision early on to use UI policies or Client scripts to make the field mandatory when it should be.

2- Read-only fields:

See #1. The solution to this problem is a little bit different though. Because security in ServiceNow can be applied in a few different ways, you’ll want to make sure to evaluate the options closely. Most of the time, Access Control Rules are your best bet through the System Security application. Depending on the situation (and how critical it is to secure the field in question) you may want to use a UI policy or a Client script to restrict access to the field. Just remember that UI policies and Client scripts only secure an object when it is loaded on the form which may leave your field open via list editing or some other method.

3- Reference qualifiers:

If the field in question is a reference field, then it’s very likely that you’ll end up using a reference qualifier to filter the records presented by the field at some point. If the tables sharing the field don’t all need the same reference qualifier (or if some don’t need one at all) then you’ll want to use an advanced reference qualifier. Constructed properly, an advanced reference qualifier gives you the ability to identify the querying table before reference qualifier is returned. This means that you can give each table its own reference qualifier, or no qualifier at all. Here’s a sample script that could be used for a Configuration item field shared between various task tables.

function myRefQualFunction() {
var answer;
switch (current.getTableName()) {
case 'incident':
answer = 'sys_class_name=cmdb_ci_computer^ORsys_class_name=cmdb_ci_service^';
break;
case 'problem':
answer = 'sys_class_name=cmdb_ci_server^';
break;
case 'change_request':
answer = 'sys_class_name=cmdb_ci_service^';
break;
case 'change_task':
answer = 'sys_class_name=cmdb_ci_service^';
break;
default: answer = '';
}
return answer;
}

4- Labels:

This isn’t a dictionary setting, but the concept here is the same. Before you go and personalize the label for a field, you really need to be aware of all of the places that field is used. Changing the label of the ‘Configuration item’ field on the Incident form to ‘Incident CI’ would work great for incidents, but not so great for Change requests. It is possible to set up a separate label entry for the same field on each individual extended table.

5- Default values:

Setting multiple default values for extended tables has now been made much simpler (as of the Spring 2010 Stable 2 release). The solution outlined below is no longer necessary for instances running on Spring 2010 Stable 2 or later. See here for details on Dictionary Overrides.

There’s only one place to set a true default value for a field…the dictionary entry for the field. Client scripts can set default values, but that value is only applied when the form loads for a particular record. Here’s a script that I’ve used before to set different default values for the ‘State’ field on the Task table. You would place this in the ‘Default value’ field on the dictionary entry of the field in question.

javascript:
switch (current.getTableName()) {
case 'incident': '1'; break;
case 'problem': '2'; break;
case 'change_request': '1'; break;
case 'change_task': '-5'; break;
default: '1';
}

6- Choice lists:

It’s very easy just to right-click on a choice field and select ‘Personalize choices’. While this option is very simple, it doesn’t always supply you with all of the information you need to make an informed decision about how and where the choice should be added. By selecting ‘Show choice list’ you can see exactly how the choice list is set up for all tables involved. Personalizing choices for a choice field is very straight-forward, you just need to be sure of the scope of the choices you are personalizing. A ‘State’ value of ‘Pending acknowledgment’ may make perfect sense in the Incident world, but might not be useful or needed for a Change task. Fortunately, you can specify unique choice values for each extended table that shares the same field.

The post One Field Shared Between Many Tables appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/scripting/one-field-shared-between-many-tables/feed/ 8