Client scripts Archives - ServiceNow Guru https://servicenowguru.com/category/client-scripts-scripting/ 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 Client scripts Archives - ServiceNow Guru https://servicenowguru.com/category/client-scripts-scripting/ 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.

]]>
Adding Icons to UI Action Buttons in ServiceNow https://servicenowguru.com/client-scripts-scripting/button-colors-icons/ https://servicenowguru.com/client-scripts-scripting/button-colors-icons/#comments Mon, 17 Apr 2017 16:05:59 +0000 https://servicenowguru.wpengine.com/?p=12498 It’s hard to believe that it’s been seven years since I wrote a post showing how you can use client scripts to manipulate the appearance of form UI action buttons. This solution has been used in countless ServiceNow instances to help add more clarity to form buttons and processes in the system. A few months

The post Adding Icons to UI Action Buttons in ServiceNow appeared first on ServiceNow Guru.

]]>
It’s hard to believe that it’s been seven years since I wrote a post showing how you can use client scripts to manipulate the appearance of form UI action buttons. This solution has been used in countless ServiceNow instances to help add more clarity to form buttons and processes in the system. A few months ago, I decided to try and see if I could expand on this client script method a bit to add even more button flexibility with the addition of an option to include an icon along with the button text. Fortunately, with the addition of a new icon set in recent ServiceNow releases, this has become pretty simple to do…all while leveraging a consistent, nice-looking icon set.


Available icons

You’ve undoubtedly seen them in various parts of the system, but you may not have realized until now that there are over 250 icons available to choose from in ServiceNow! You can use these icons in various ways (client scripts, UI pages, UI macros, CMS and Service Portal), including with UI action buttons as I show here. All you have to do to show an icon is to add a class attribute with a name matching the icon you want to add.
ServiceNow had previously published a style guide that you could reference to view all of the icons (and corresponding names to reference them by). For the time being, you can access the icons in your instance by navigating to https://your_instance.service-now.com/styles/retina_icons/retina_icons.html

The following script can be used in any standard form client script. The key is the ‘transformButton’ function at the bottom. This could be included as a global UI script in your instance so that you don’t need to include it in every single client script. Once that’s in place (whether in a global UI script or in the client script itself) you can just call ‘transformButton’ with the appropriate parameters to change the button however you want. The parameters used are as follows…

  1. UI action name (Mandatory)
  2. Button background color (Optional)
  3. Button text color (Optional)
  4. Button icon name (Optional)
function onLoad() {
//Change the color of the 'Approve' button to green
transformButton('approve', '#77FF77', 'white', 'icon-success-circle');
//Change the color of the 'Reject' button to red
transformButton('reject', '#FF0022', 'white', 'icon-error-circle');
//Change the color of the 'Info' button to blue
transformButton('info_button', '#31708f', 'white', 'icon-info');
//Change the color of the 'Warning' button to yellow
transformButton('warning_button', '#f0ad4e', 'white', 'icon-warning-circle');
}

function transformButton(buttonID, buttonBackgroundColor, buttonTextColor, buttonIconName) {
try{
//Find the button(s) by ID and change the background color
$$('button[id=' + buttonID + ']').each(function(elmt) {
elmt.style.backgroundColor = buttonBackgroundColor;
if(buttonTextColor){
elmt.style.color = buttonTextColor;
}
if(buttonIconName){
elmt.addClassName(buttonIconName);
//Add some spacing between the icon and button label
elmt.innerHTML = ' ' + elmt.innerHTML;
}
});
}catch(e){}
}

The post Adding Icons to UI Action Buttons in ServiceNow appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/button-colors-icons/feed/ 19
Client Side Dates in ServiceNow https://servicenowguru.com/client-scripts-scripting/client-side-dates-in-servicenow/ https://servicenowguru.com/client-scripts-scripting/client-side-dates-in-servicenow/#comments Wed, 22 Feb 2017 13:29:15 +0000 https://servicenowguru.wpengine.com/?p=12051 Dates on the client side in ServiceNow have always been challenging. Javascript has its own complexities in this regard and mixing this with ServiceNow’s date formats and user preferences can make it a nightmare. Here we walk through some of the methods of working with client side dates that make it MUCH simpler and allow

The post Client Side Dates in ServiceNow appeared first on ServiceNow Guru.

]]>
Dates on the client side in ServiceNow have always been challenging. Javascript has its own complexities in this regard and mixing this with ServiceNow’s date formats and user preferences can make it a nightmare.

Here we walk through some of the methods of working with client side dates that make it MUCH simpler and allow us to avoid the situation of having to return to the server via GlideAjax for most, if not all, date calculations.

ServiceNow Date Formats drop-down

If you’re here as a reference and just need the key code snippets, here you go. Basically, to get a javascript date from a ServiceNow date field value do this:

var date_number = getDateFromFormat(g_form.getValue('the_date_field'), g_user_date_format);
var my_date = new Date(date_number);

Or, from a Date/Time field do this:

var date_number = getDateFromFormat(g_form.getValue('the_date_time_field'), g_user_date_time_format);
var my_date = new Date(date_number);

The Details

Working with dates on the client side of things in ServiceNow has always been a challenge. Part of this is just due to Javascript and the challenges associated with dates and the other is ServiceNow. Given that users can have their own date format makes it even more challenging. That said, we are given some tools (albeit undocumented ones) that can help improve the situation.

I ran across some information a while back (thanks to John Roberts) that helps the situation drastically. The key comes down to a couple global variables defined by the system as well as function that helps use those variables.

The variables give us the date and datetime formats for the logged in user, and the function lets us use those to get something we can work with a little easier.

User datetime format: g_user_date_time_format
User date format: g_user_date_format

These used with the getDateFromFormat function gives us an easy way to get a value for the date (essentially a Unix Timestamp). That value can then be used directly or immediately passed into a Javascript Date object to allow for reformatting, testing, or whatever else is needed.

Here are a few functions that I put together to simplify the date validation process that is so often needed.

Test for valid DateTime based on user format:

function isValidDateTime(value){
  if(value == '' || value == undefined || value == null){
    return false;
  }
  return(getDateFromFormat(value, g_user_date_time_format) != 0);
}

Test for valid Date based on user format:

function isValidDate(value){
  if(value == '' || value == undefined || value == null){
    return false;
  }
  return (getDateFromFormat(value, g_user_date_format) != 0);
}

To take this a step further, you could easily add comparisons of dates or add custom date formats based on the values.

One thing to keep in mind with this, depending on where the date is coming from you may still have two date formats. Any of the dates that will work as shown are going to be the values in fields on a form or the Display Value of the date. If you’re getting something from the server (e.g. via GlideAjax) as just a value then it will be stored in the regular system format of YYYY-MM-DD HH:MM:SS.

An additional example suggested by a co-worker (thank Thomas) to validate that the date is within an hour

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
  if (isLoading || newValue == '') {
    return;
  }

  //To change the date range from 1 hour, change var minutes_from_now to desired amount time
  var minutes_from_now = 60;
  var date_obj = new Date(getDateFromFormat(newValue, g_user_date_time_format));
  var future_date = new Date(new Date().getTime() + minutes_from_now*60000);
  if(future_date < date_obj){
    alert("Time is too far out");
  }
}

Hopefully this helps save you some of the frustration I’ve experienced over the years when dealing with client side dates in ServiceNow.

The post Client Side Dates in ServiceNow appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/client-side-dates-in-servicenow/feed/ 5
Granular Control of Form Tab Toggle Behavior via Client Scripts https://servicenowguru.com/client-scripts-scripting/toggle-tabs-client-scripting/ https://servicenowguru.com/client-scripts-scripting/toggle-tabs-client-scripting/#comments Wed, 30 Apr 2014 15:56:44 +0000 https://servicenowguru.wpengine.com/?p=5259 This post comes to you from ServiceNow’s Knowledge14 event in San Francisco. It’s exciting to see all of the new innovations that ServiceNow is introducing in the upcoming releases. I’ve been very involved with my company, Crossfuze Solutions, as a sponsor of the conference and it’s been incredibly rewarding to showcase our solutions and talk

The post Granular Control of Form Tab Toggle Behavior via Client Scripts appeared first on ServiceNow Guru.

]]>
This post comes to you from ServiceNow’s Knowledge14 event in San Francisco. It’s exciting to see all of the new innovations that ServiceNow is introducing in the upcoming releases. I’ve been very involved with my company, Crossfuze Solutions, as a sponsor of the conference and it’s been incredibly rewarding to showcase our solutions and talk to so many of you about how Crossfuze and ServiceNow Guru have helped you to be successful in implementing and enhancing ServiceNow. If you’re here at the conference, please stop by booth #421 during the expo hours and say hello!

Today’s post comes in response to a question posted on the ServiceNow community about providing more granular control over the form and list tabbing behavior for specific tables and conditions. If you’re familiar with ServiceNow, you know that this cannot be done natively and that tabbing is based off of a user preference that is enforced globally for the user accessing the system. Continue reading to see how to add more flexibility to your form tab behavior!

Granular Tab Control

‘tabbed.forms’ User Preference

As background, the first thing you should know is that the user preference (accessed from the ‘User Preferences’ module) that controls this behavior is ‘tabbed.forms’. You can set this globally as a default or set it individually directly from the table record if needed.

Controlling the ‘tabbed.forms’ User Preference from a client script

In most cases, simply clicking the icon in the top-right corner is all you need to toggle tabbing within your forms. In the event that you need to do that through scripting, a client script is your answer. You can toggle the tabbing globally for a user with the following code…

tabs2Toggle();

Granular control…WITHOUT impacting the user preference

The problem with the script above is that YOU’LL PROBABLY NEVER USE IT! I can’t think of a single scenario where you would want to toggle tabs and have that user preference enforced for a user globally. You’d just set the global default preference and be done with it.

This becomes MUCH more useful though if you can control the tabbing behavior without modifying the system property. Maybe you want to just expand the form sections for a particular table based on a specific condition without impacting the list tabs and without impacting the behavior anywhere else. The following can be used in your client scripts to accomplish this…

g_tabs2Sections.deactivate(); //Deactivate form tabs
g_tabs2Sections.activate(); //Activate form tabs
g_tabs2List.deactivate(); //Deactivate list tabs
g_tabs2List.activate(); //Activate list tabs

Want to learn more about controlling the behavior of tabs and form sections in ServiceNow? Check out these other articles for more information!

The post Granular Control of Form Tab Toggle Behavior via Client Scripts appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/toggle-tabs-client-scripting/feed/ 3
Overriding ServiceNow Form View Inheritance https://servicenowguru.com/client-scripts-scripting/overriding-servicenow-form-view-inheritance/ https://servicenowguru.com/client-scripts-scripting/overriding-servicenow-form-view-inheritance/#comments Fri, 20 Sep 2013 13:59:41 +0000 https://servicenowguru.wpengine.com/?p=5034 6+ years ago when I was an admin first being introduced to ServiceNow, I remember being blown away by how simple it was to personalize forms, add fields, and design custom form views. Custom views are very easy to make, but I’m always hesitant to recommend them due to the unintended complexity they can cause.

The post Overriding ServiceNow Form View Inheritance appeared first on ServiceNow Guru.

]]>
6+ years ago when I was an admin first being introduced to ServiceNow, I remember being blown away by how simple it was to personalize forms, add fields, and design custom form views. Custom views are very easy to make, but I’m always hesitant to recommend them due to the unintended complexity they can cause. The biggest issue with the ‘view’ concept in ServiceNow is that the system insists on forcing that form view onto every record referenced from within it. This issue exists in every ServiceNow instance today. In this article, I’ll explain why this can be a huge problem, and finally, a good way to break the ServiceNow form view inheritance cycle!

ServiceNow Form View Inheritance

The problem:

Here’s an example that most likely exists in your system (and certainly does in ServiceNow demo systems) to help illustrate the problem. If you go to your system and open an emergency change record, you’ll probably notice that it displays the ‘Emergency’ view in the top-left corner of the change form. That’s great, but when you click the reference icon for the ‘Requested by’ or ‘Assigned to’ fields, you’ll see that the system applies that view name (even though it doesn’t exist for that table) to the referenced record form. Then if you click on the ‘Company’ or ‘Department’ referenced record on the user form, you’ll notice that the ‘Emergency’ view name is carried over there as well!

It’s important to note, that the system is not actually creating new views as this happens. It’s simply cascading the previous form view to any other record you navigate to. The label of ‘Emergency’ is actually the smaller, cosmetic-only, issue. The larger issue is when you decide personalize that user or department form as an admin. You’ll most likely end up creating a brand-new view named ‘Emergency’ that applies to your user table! Now you’ve got an extra view and your changes won’t show up in the right place anyway because you meant to customize the ‘Default’ view instead…and you better hope nobody decides to reference that new, garbage view in a module or list definition and have it end up propagating the problem even further.

So, in short, this is a HUGE problem, and one that I’ve struggled with for the past 6+ years. It’s one ‘feature’ of ServiceNow that I’ve never understood, and this alone always makes me very hesitant to recommend the use of views to any of my clients. Fortunately there are a couple of things you can do to work around this…one that’s been around for as long as views have, and one that I came up with yesterday that easily allows you to override view inheritance for any table in the system.

Option 1: View rules

I’m a big fan of view rules and I’ve used them (primarily in change management) for a long time. They allow you to force a particular view on a particular table, for a particular subset of records. To use the change example again, you could set up a view rule to force the Default, Emergency, and Routine form views to display Comprehensive, Emergency, and Routine changes in their own respective views with their own sets of fields and related lists.

This is extremely handy, and can help break view inheritance because it forces a particular view for records in a table. The downside of this is that it’s not really practical to set up a view rule for every record table referenced from the change table just so you can overcome this problem. You could end up with a separate view rule for hundreds of tables!

Option 2: A better way…

Shown below is an example script that we’ve started using at Crossfuze in our Change turnkey product. This script runs on load of a particular table (Change request for example) and manipulates the form to remove any trace of a given view from the reference or related list links. A single client script can solve this issue for you on any table where you choose to set up custom views!

‘Override view inheritance’ Client Script
Name: Override view inheritance
Table: Change request [change_request] Type: OnLoad
Script:

function onLoad() {
//Override all non-default change view inheritance for records referenced on change
overrideViewInheritance('routineChange', '');
overrideViewInheritance('emergencyChange', '');
}function overrideViewInheritance(oldView, newView) {
try{
//Override reference field link view inheritance
if($('sysparm_view').value == oldView){
$('sysparm_view').value = newView;
}

//Override related list link view inheritance
$('related_lists_wrapper').select('a.linked').each(function(elmt) {
elmt.href = elmt.href.gsub('sysparm_view=' + oldView,'sysparm_view=' + newView);
});
}catch(e){}
}

The post Overriding ServiceNow Form View Inheritance appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/overriding-servicenow-form-view-inheritance/feed/ 9
Reload a Form or Related list from a Client Script https://servicenowguru.com/client-scripts-scripting/reload-form-related-list-client-script/ https://servicenowguru.com/client-scripts-scripting/reload-form-related-list-client-script/#comments Thu, 04 Oct 2012 13:03:30 +0000 https://servicenowguru.wpengine.com/?p=4565 This post comes in response to a forum question about how to reload a form or related list from a client script. This can come in extremely handy in the right situation. In the past, I’ve used scripts like these to refresh information on the form in response to a back-end server update of some

The post Reload a Form or Related list from a Client Script appeared first on ServiceNow Guru.

]]>
This post comes in response to a forum question about how to reload a form or related list from a client script. This can come in extremely handy in the right situation. In the past, I’ve used scripts like these to refresh information on the form in response to a back-end server update of some sort. Here are a couple of code examples that show how to trigger these reload actions.


Reload a form

Reloading a form is simple, and it’s already built-in with the ‘Reload form’ context menu action.
Reload Form Action

The client script to reload a form looks like this…

reloadWindow(window);

Refresh a related list

Refreshing a related list is a bit more complex since you need to correctly identify the related list you wish to refresh. You can do that by right-clicking the related list header and selecting ‘Personalize->List Control’. The list control will show you the name of the related list that you need to use. In the screenshot below, the name of the ‘Affected CIs’ related list is ‘task_ci.task’.
List Control

Once you’ve identified the name of the related list, you can refresh it from any client-side script by using the following code (adding your list name where appropriate).

GlideList2.get(g_form.getTableName() + '.YOUR_RELATED_LIST_NAME_HERE').setFilterAndRefresh('');

So if you wanted to set up a client-side ‘Refresh’ UI action for the ‘Affected CIs’ related list, you could do so with the following setup. Notice the use of ‘task_ci.task’ to identify the related list in the ‘Script’ section.

‘Refresh’ related list UI action
Name: Refresh
Table: task_ci
Client: true
List banner button: true
Onclick: refreshAffectedCIs()
Condition: RP.isRelatedList()
Script:

function refreshAffectedCIs(){
GlideList2.get(g_form.getTableName() + '.task_ci.task').setFilterAndRefresh('');
}

Refresh an embedded related list

It’s also possible to refresh an embedded related list.

try {
var elementLookup = $$('div.tabs2_list');
var listName = "Affected CIs";
for (i = 0; i != elementLookup.length; i++) {
if (elementLookup[i].innerHTML.indexOf(listName) != -1) {
var listHTML = elementLookup[i].id.split('_');
var listID = listHTML[0];
nowRefresh(listID);
}
}
}
catch (err) {
//alert(err.message);
}

function nowRefresh(id) {
GlideList2.get(id).refresh('');
}

The post Reload a Form or Related list from a Client Script appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/reload-form-related-list-client-script/feed/ 23
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
Change Form Header Background Color https://servicenowguru.com/client-scripts-scripting/change-form-header-background-color/ https://servicenowguru.com/client-scripts-scripting/change-form-header-background-color/#comments Wed, 11 Jan 2012 17:35:15 +0000 https://servicenowguru.wpengine.com/?p=4236 Just a quick scripting tip today based on a solution that I helped someone with on the ServiceNow community site. The request I received was to be able to change the form header background color based on changes to values in a record. You’re probably aware that ServiceNow provides a global CSS property to set

The post Change Form Header Background Color appeared first on ServiceNow Guru.

]]>
Just a quick scripting tip today based on a solution that I helped someone with on the ServiceNow community site. The request I received was to be able to change the form header background color based on changes to values in a record. You’re probably aware that ServiceNow provides a global CSS property to set the form and list header color. This is usually one of the first things that gets customized during a deployment. The global property can be found by navigating to System Properties -> CSS, and changing the ‘Banner and list caption background color’ property.

This request required something more dynamic so that the color could change based on specific table and record values and specific changes to a specific form. In order to accomplish this, I came up with a simple client script that can be used anywhere you need it.

Red Header Background

This same idea can be applied to form buttons as well. Check out this article to find out how!

You can add this script snippet to any client script. Just change the ‘backgroundColor’ variable to the color of your choice!

function onLoad() {
//Change the color of all form section headers
var backgroundColor = 'red';
$$('.navbar').each(function(elmt) {
elmt.style.backgroundColor = backgroundColor;
});
}

The post Change Form Header Background Color appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/change-form-header-background-color/feed/ 18
Customizing the dirty form alert popup https://servicenowguru.com/system-ui/custom-dirty-form-message/ https://servicenowguru.com/system-ui/custom-dirty-form-message/#comments Wed, 14 Dec 2011 13:49:16 +0000 https://servicenowguru.wpengine.com/?p=4192 I had a colleague come to me recently for help on a client issue. The customer wanted two things; the first was to set up the capability to warn users when they were navigating away from a modified form without saving it, but to do this only on selected forms rather than globally. The second

The post Customizing the dirty form alert popup appeared first on ServiceNow Guru.

]]>
I had a colleague come to me recently for help on a client issue. The customer wanted two things; the first was to set up the capability to warn users when they were navigating away from a modified form without saving it, but to do this only on selected forms rather than globally. The second was to modify the text included in the alert dialog to be whatever they wanted. In this post I’ll explain some of the options that ServiceNow provides in this area and how you can get even more flexibility and control over this behavior through scripting.

Custom Dirty Form Alert

The first thing to know about this functionality is that its main purpose is to identify that fields on a form have been modified, and alert the user if they try to navigate away from one of these forms if the record hasn’t been saved. I’ve touched on this topic before in an article I wrote about identifying modified fields. Because this is a common problem, ServiceNow actually includes a property (which is active by default) to present this alert. You’ve probably noticed this alert as you’ve worked in your ServiceNow instance…

Default Dirty Form Alert

The name of the property that controls this behavior is ‘glide.ui.dirty_form_support’ and can be changed by accessing the property through the ‘sys_properties’ table. This property works globally across an instance and causes the alert to display for any standard forms (meaning this isn’t going to work in the service catalog) so there’s not a whole lot you can do to control the functionality. One thing you can do easily is control part of the message contained in the alert. I say “part” because the dialog is actually a standard javascript/browser behavior so that limits your control a bit. The part you can customize is the line in the alert that looks like this…

Changes have been made. Continuing will discard the changes.

This text is actually accessed via a ‘Message’ record in the system that is passed from the server to the client when a form is rendered. You can find and modify this global message by navigating to ‘System UI -> Messages’ and looking for the entry as shown here…

Dirty Form Alert Message

Beyond the basics…

While the information above is useful, it still doesn’t solve the issues I described above…warning ONLY on selected forms to selected users, and controlling the text on these selective dialogs. As is often the case, a carefully-crafted client script can provide the needed flexibility.

When a form loads in your browser, it comes with a ‘window.onbeforeunload’ object that detects when the window is closed or navigated away from. In most cases there’s nothing associated with this event, but in cases like this, you can trigger specific things (like an alert). The way this works is kind of unique for javascript event handlers. In this case, the ‘window.onbeforeunload’ event gets attached to a function whose purpose is to return text to be inserted into the alert dialog. By attaching a function to this event in a client script you can override the default message and apply the message and alert selectively across different forms and for different roles and users.

The script below is the simplest example but you can add client-side checks for roles and other things if you want. All you have to do is change the ‘YOUR CUSTOM MESSAGE HERE’ line to

Please note that this client script is an override of the dirty form system property described above. If the system property is active, then it will behave normally for any form that doesn’t include a custom client script. The client script also has no access to the message record described above so the alert message is defined within the script itself.
‘Custom Dirty From Alert’
Name: Custom Dirty From Alert
Table: Wherever you want!
Type: onLoad
Script:

function onLoad() {
//Add the 'onbeforeunload' event
window.onbeforeunload = function() {
//If we're leaving a modified form without a submit
if (!g_form.submitted && g_form.modified) {
//Add the custom dialog message here
return 'YOUR CUSTOM MESSAGE HERE.';
}
}
}

Custom Dirty Form Alert

The post Customizing the dirty form alert popup appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/system-ui/custom-dirty-form-message/feed/ 17
Attach an event listener to a related list button https://servicenowguru.com/client-scripts-scripting/attach-event-listener-related-list-button/ https://servicenowguru.com/client-scripts-scripting/attach-event-listener-related-list-button/#comments Thu, 01 Dec 2011 17:37:18 +0000 https://servicenowguru.wpengine.com/?p=4065 Recently a colleague asked me for assistance with a customer request. The requirement was to pop up an information or alert message when a user clicked the ‘Edit’ button on the ‘Affected CIs’ related list. The alert message would give them some information or a warning, allow the user to confirm, and then continue on

The post Attach an event listener to a related list button appeared first on ServiceNow Guru.

]]>
Recently a colleague asked me for assistance with a customer request. The requirement was to pop up an information or alert message when a user clicked the ‘Edit’ button on the ‘Affected CIs’ related list. The alert message would give them some information or a warning, allow the user to confirm, and then continue on to the edit screen. ServiceNow gives you a lot of control over the behavior of some buttons with the configuration of UI actions. There are other buttons in the system, however, that you can’t easily control…including many related list buttons. In order to meet this requirement I created an ‘onLoad’ client script to attach an event listener and onclick function to the necessary button. Read on to see how it’s done!

Related List Event

There are two important pieces of this script that make it work. The first piece is to correctly identify the related list button that you want to respond to. For this script that requires two pieces of information, the button text (‘Edit…’) and the related list identifier.
The related list identifier is the tricky one to come up with. The surest way to find it is to use a dom inspector like firebug to identify it. It does follow a predictable pattern though so you can usually come up with the correct thing by piecing a few bits of information together like this…

.._list

So, the ‘Parent incident’ related list on the incident table is referenced by this ID…
incident.incident.parent_incident_list

And the ‘Affected CIs’ related list on the change request table is referenced by this ID…
change_request.task_ci.task_list

The second important piece of this script is the ‘Event.observe’ line (and the Firefox workaround above it). This is how we attach a new ‘onClick’ event to the button we’ve identified.

The full script looks like this. You can modify it for your own use by changing the buttonText and listID variables to identify the correct button. Then you tell it what to do when the button is clicked by putting your own client-side javascript inside of the ‘customOnClick’ function.

function onLoad() {
//Attach an event listener to the 'Edit' button on the 'Affected CIs' related list
var buttonText = 'Edit...';
var listID = 'change_request.task_ci.task_list';
//Find all buttons for the 'Affected CIs list'
var buttons = $(listID).select('button');
buttons.each(function(elmt) {
if(elmt.innerHTML.indexOf(buttonText) > -1){
//If the button text matches attach an event listener
Event.observe(elmt, 'click', customOnClick);
}
});
}

function customOnClick(){
alert('You clicked me!');
}

The post Attach an event listener to a related list button appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/client-scripts-scripting/attach-event-listener-related-list-button/feed/ 4