Client scripts Archives - ServiceNow Guru https://servicenowguru.com/tag/client-scripts/ ServiceNow Consulting Scripting Administration Development Tue, 28 May 2024 20:09:56 +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/tag/client-scripts/ 32 32 Client & Server Code in One UI Action https://servicenowguru.com/ui-actions-system-ui/client-server-code-ui-action/ https://servicenowguru.com/ui-actions-system-ui/client-server-code-ui-action/#comments Thu, 20 May 2021 10:45:36 +0000 https://servicenowguru.wpengine.com/?p=1962 Most Service-now administrators and consultants know how to configure and use UI Actions. UI Actions are UI elements that can show up on a form or a list as a button, link, or context menu. When these UI elements are clicked they execute some JavaScript. Most of the time UI Actions are used to perform

The post Client & Server Code in One UI Action appeared first on ServiceNow Guru.

]]>
Most Service-now administrators and consultants know how to configure and use UI Actions. UI Actions are UI elements that can show up on a form or a list as a button, link, or context menu. When these UI elements are clicked they execute some JavaScript. Most of the time UI Actions are used to perform some server-side update to a record or records. In other cases, you can use the ‘Client’ checkbox on the UI Action record to execute some client-side JavaScript (including checking for mandatory fields).

But what if you need to do both? The classic case is when you want to click a button to make an update to a record, but only if the user has provided the correct input first. An example would be a ‘Reopen Incident’ button that changes the state on an incident record from ‘Resolved’ to ‘Active’. Usually you want to require the user to provide some sort of comment or additional information explaining why they are reopening the ticket. The problem is that you don’t always want the ‘Comments’ field to be mandatory so the validation needs to happen at the time the ‘Reopen Incident’ button gets clicked. Validation of mandatory fields needs to happen client-side but the update to your record needs to happen server-side. How can you accomplish both of these things with a single UI Action? This article shows you how.



The basic format for using a Client Script and Business Rule in the same UI Action looks something like this…

UI Action Template
Name: -Button Name-
Action name: -button_action_name- (Should be unique per button on form and gets called from the UI Action script)
Client: True (MUST be checked)
Form button/Form Context Menu/Form Link: (UI Action must be one of these ‘Form’ types)
Onclick: -runClientCode();- (Points to the function in your script that should be run when the UI Action gets clicked)
Script:

//Client-side 'onclick' function
function runClientCode(){
if( == false){
return false; //Abort submission
}
//Call the UI Action and skip the 'onclick' function
gsftSubmit(null, g_form.getFormElement(), ''); //MUST call the 'Action name' set in this UI Action
}//Code that runs without 'onclick'
//Ensure call to server-side function with no browser errors
if(typeof window == 'undefined')
runBusRuleCode();//Server-side function
function runBusRuleCode(){
current. = ;
current.update();
gs.addInfoMessage('You did it!');
action.setRedirectURL(current);
}

So why does this work? I had to go to a Service-now developer to find out. The reason is that UI Actions can run scripts at two different times. The first time is when the UI Action gets clicked. When you define a ‘Client’ UI Action you also give that UI Action the name of a function in your ‘Script’ field to execute. This function has to be called explicitly (through the ‘onclick’ event) or it doesn’t run at all.
The second time is on the way to the server. This is how any UI Action without the ‘Client’ checkbox selected gets run. On the way to the server the entire UI Action script gets executed regardless of whether or not the ‘Client’ checkbox is checked. What this means is that any script you include in your UI Action that isn’t enclosed in a function will be run on the way to the server. The script above takes advantage of this fact by making a specific call to the ‘Client’ function, performing client-side validation, and then the UI Action calls itself if the client-side validation passes.
When the UI Action calls itself it bypasses the ‘onclick’ function because the button didn’t get clicked the second time. So the script continues to the first point where there is something to execute. At that point you can call your Server-side function! The only thing you need to be careful of is that you only call the Server-side function if the script isn’t running in the client anymore. That’s what the check in the middle does…and eliminates any browser errors saying that ‘current’ (or any other Server-side function or object) isn’t defined.

Here is a solution I’ve used in the past to give users the ability to reopen an incident record. The solution uses a UI Action button to check if the ‘Comments’ field has been filled in (this is the ‘Client-side’ portion). If the validation passes, then the incident record gets updated.

Reopen Incident UI Action

Note that this script uses the ‘State’ field rather than the ‘Incident State’ field. In my opinion, it is much better to consolidate all of your state fields into one using the ‘State’ field at the task level as described here.

Name: Reopen Incident
Action name: reopen_incident
Client: True
Form button: True
Onclick: reopen();
Condition: current.state == 6
Script:

//Client-side 'onclick' function
function reopen(){
if(g_form.getValue('comments') == ''){
//Remove any existing field message, set comments mandatory, and show a new field message
g_form.hideFieldMsg('comments');
g_form.setMandatory('comments', true);
g_form.showFieldMsg('comments','Comments are mandatory when reopening an Incident.','error');
return false; //Abort submission
}
//Call the UI Action and skip the 'onclick' function
gsftSubmit(null, g_form.getFormElement(), 'reopen_incident'); //MUST call the 'Action name' set in this UI Action
}

//Code that runs without 'onclick'
//Ensure call to server-side function with no browser errors
if(typeof window == 'undefined')
serverReopen();

function serverReopen(){
//Set the 'State' to 'Active', update and reload the record
current.state = 2;
current.update();
gs.addInfoMessage('Incident ' + current.number + ' reopened.');
action.setRedirectURL(current);
}

The post Client & Server Code in One UI Action appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/ui-actions-system-ui/client-server-code-ui-action/feed/ 59
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
UI Info and Error Message Cheat Sheet https://servicenowguru.com/scripting/ui-info-error-message-cheat-sheet/ https://servicenowguru.com/scripting/ui-info-error-message-cheat-sheet/#comments Wed, 10 Oct 2012 12:48:52 +0000 https://servicenowguru.wpengine.com/?p=4576 Information messages are a great way to provide UI feedback to end users as they interact with the various forms in your instance. This article describes the various methods you can use to display information messages to the users accessing your ServiceNow system. Client-side UI Messages The following methods are designed for use in client-side

The post UI Info and Error Message Cheat Sheet appeared first on ServiceNow Guru.

]]>
Information messages are a great way to provide UI feedback to end users as they interact with the various forms in your instance. This article describes the various methods you can use to display information messages to the users accessing your ServiceNow system.

Client-side UI Messages

The following methods are designed for use in client-side scripting (primarily client scripts and UI policies). As such, they are used on standard forms and on catalog forms and can run on load or submit of a form, or on change of a field value.

Client-side Info and Error Messages
Function/MethodDescriptionUsage
addInfoMessage(message)Displays an informational message at the top of the form with a blue information icon and a light-blue background.g_form.addInfoMessage('Form Info Message Text');
addErrorMessage(message)Displays an error message at the top of the form with a red error icon and a light-red background.g_form.addErrorMessage('Form Error Message Text');
clearOutputMessagesHides ALL form info and error messages. There is no way to remove form info and error messages individually.GlideUI.get().clearOutputMessages();
showFieldMsg(input, message, type, [scrollForm])Displays either an informational or error message under the specified form field (either a control object or the name of the field). Type may be either "info" or "error." If the control or field is currently scrolled off the screen, it will be scrolled to.

A global property (glide.ui.scroll_to_message_field) is available that controls automatic message scrolling when the form field is offscreen (scrolls the form to the control or field).

Optional: Set scrollForm to false to prevent scrolling to the field message offscreen.

Parameters:
input - specifies the name of the field or control.
message - the message to be displayed.
type - error or info.
scrollForm (optional) - true to scroll to message if offscreen, false to prevent this scrolling.
//Field info message
g_form.showFieldMsg('priority','Priority is low.','info');

//Field error message
g_form.showFieldMsg('impact','Priority is high!','error');
hideFieldMsg(input, [clearAll])Hides info and error messages for a single field.g_form.hideFieldMsg('impact', true);
hideAllFieldMsgs([type])Hides all field info and error messages.

Optional: Provide type to hide only "info" or "error" messages.
g_form.hideAllFieldMsgs();
flash(widgetName, color, count)Flashes the specified color the specified number of times in the field.

Parameters:
widgetName - Specifies the element with (table name).(fieldname).
color - RGB or CSS color
count - How long the label will flash.
use 2 for a 1-second flash
use 0 for a 2-second flash
use -2 for a 3-second flash
use -4 for a 4-second flash
g_form.flash("incident.number", "#CC0000", -2);

Server-side UI Messages

Although messages will always be displayed client-side, they are often initiated from a server-side script like a business rule, record producer script, or script include. Messages initiated from server-side scripts can appear at the top of any form or list and are typically triggered by a database action such as a record insert, update, or delete.

Server-side Info Messages
Function/MethodDescriptionUsage
addInfoMessage(message)Displays an informational message for the current session with a blue information icon and a light-blue background.

Can also include HTML in the message! Note that I've replaced the greater than and less than symbols with brackets in the HTML usage example to get it to display correctly here. You'll need to change the brackets back to standard HTML to get it to work in your instance.
gs.addInfoMessage('Session Info Message Text');

//Info message with HTML formatting
//Create the html contents of the information message
var link = '[a href="incident.do?sys_id=' + current.sys_id + '" class="breadcrumb" ]' + current.number + '[/a]';
var message = 'Incident ' + link + ' has been created. ';
message += 'Thank you for your submission.';

//Add the information message
gs.addInfoMessage(message);
addErrorMessage(message)Displays an error message for the current session with a red error icon and a light-red background.

Can also include HTML in the message!
gs.addErrorMessage('Session Error Message Text');
flushMessages()Clears any existing session info or error messages to prevent them from being displayed.//Clear any session info or error messages
gs.flushMessages();

UI Notifications

UI Notifications are an unusual class that can be used for refreshing elements such as the navigation pane or for displaying messages in response to changes in database tables. For more information about UI Notifications, check out the following articles:

The post UI Info and Error Message Cheat Sheet appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/scripting/ui-info-error-message-cheat-sheet/feed/ 18
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
Refresh the Left Navigation Pane via Script https://servicenowguru.com/system-ui/refresh-left-navigation-pane-script/ https://servicenowguru.com/system-ui/refresh-left-navigation-pane-script/#comments Tue, 22 May 2012 15:20:34 +0000 https://servicenowguru.wpengine.com/?p=4441 Here’s a quick scripting tip for today. Have you ever needed to refresh the left navigation menu in response to some script action? I don’t think this requirement comes up often, but I just had somebody ask me a question related to this so I figured I would find out how it can be done.

The post Refresh the Left Navigation Pane via Script appeared first on ServiceNow Guru.

]]>
Here’s a quick scripting tip for today. Have you ever needed to refresh the left navigation menu in response to some script action? I don’t think this requirement comes up often, but I just had somebody ask me a question related to this so I figured I would find out how it can be done.


The code below is taken directly from a ServiceNow demo instance, and you can find it in your own instance as well. The server-side example comes from a business rule on the ‘sys_app_module’ table, and the client-side example comes from digging around in the DOM. :)

Server-side refresh trigger

–For use in business rules, UI actions, etc.

// tell the UI to refresh the navigator
var notification = new UINotification('system_event');
notification.setAttribute('event', 'refresh_nav');
notification.send();

Client-side refresh trigger

–For use in client scripts, UI policies, etc.

getNavWindow().location = 'navigator_change.do';

 

For another way to use UI Notifications, take a look at our article Display Messages With UI Notifications.

The post Refresh the Left Navigation Pane via Script appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/system-ui/refresh-left-navigation-pane-script/feed/ 9
CI UI Macro Actions for the Affected CIs List https://servicenowguru.com/cmdb/show-bsm-ci-map-affected-cis-related-list/ https://servicenowguru.com/cmdb/show-bsm-ci-map-affected-cis-related-list/#comments Wed, 18 Jan 2012 13:12:25 +0000 https://servicenowguru.wpengine.com/?p=4252 The ability to associate Affected Configuration Items against a task is one of the most basic pieces of the various task forms in ServiceNow. ServiceNow gives you the ‘Configuration Item’ field to associate a single CI and the ‘Affected CIs’ related list in the event that your task needs to be associated to multiple CIs.

The post CI UI Macro Actions for the Affected CIs List appeared first on ServiceNow Guru.

]]>
The ability to associate Affected Configuration Items against a task is one of the most basic pieces of the various task forms in ServiceNow. ServiceNow gives you the ‘Configuration Item’ field to associate a single CI and the ‘Affected CIs’ related list in the event that your task needs to be associated to multiple CIs. I’ve written before about the benefits of tracking all of this information in one place to simplify reporting and usage requirements. During an onsite visit with a customer this week I noticed another opportunity to improve the functionality of the ‘Affected CIs’ related list. It would be very useful to be able to right-click items in the ‘Affected CIs’ related list and show a BSM Map or associated tasks just like you can do for the ‘Configuration Item’ field UI Macro icons. This post will show you how you can set these list context UI Actions up in your instances.

Configuration Item Reference Icons

Configuration Item Context Actions

Add a UI Action Context Menu to Show a BSM Map for a CI

This UI Action allows you to access (via a right-click context menu) a Business Service Map for any Configuration Item listed in the ‘Affected CIs’ related list.

Special thanks to Peter Oneppo for building the bulk of this script during a customer visit we had together this week!

‘Show CI map’ UI action
Name: Show CI map
Table: CI’s Affected (task_ci)
List context menu: True
Show insert: True
Show update: True
Client: True
Onclick: showBSMMapList()
Condition: gs.hasRole(‘itil’) && RP.isRelatedList()
Script:

function showBSMMapList() {
//Retrieve the 'Affected CI' record
var sysId = typeof rowSysId == 'undefined' ? gel('sys_uniqueValue').value : rowSysId;
var gr = new GlideRecord('task_ci');
gr.get(sysId);//Build the BSM map URL
var attribs = 'table=cmdb_ci';
attribs += ',id=' + gr.ci_item;
attribs += ',level=4';
attribs += ',ref=' + g_form.tableName + '.cmdb_ci';
attribs += ',ciview=';
attribs += ',restack=true';
var url = new GlideURL('bsm_map2.do');
url.addParam('sysparm_nameofstack', 'bsm');
url.addParam('sysparm_attributes', attribs);

//Open the BSM map URL in a new window
var w = getTopWindow();
w.popupOpenFocus(url.getURL(), 'show_bsm_map', 950, 700, '', false, false);
}

If you’ve set up the UI Action correctly, you should now be able to right-click a row in the ‘Affected CIs’ related list and display a BSM map by clicking the ‘Show CI Map’ option.

CI Context Action - CI BSM Map

Add a UI Action Context Menu to Show Related Tasks for a CI

Using a similar concept to that described above, you can create a context menu UI Action to display a dialog containing all associated, active tasks for any Configuration Item in the ‘Affected CIs’ related list.

‘Show Related Tasks’ UI action
Name: Show Related Tasks
Table: CI’s Affected (task_ci)
List context menu: True
Show insert: True
Show update: True
Client: True
Onclick: showTasksDialogList()
Condition: gs.hasRole(‘itil’) && RP.isRelatedList()
Script:

function showTasksDialogList() {
//Retrieve the 'Affected CI' record
var sysId = typeof rowSysId == 'undefined' ? gel('sys_uniqueValue').value : rowSysId;
var gr = new GlideRecord('task_ci');
gr.get(sysId);//Create and display the GlideDialogWindow
var w = new GlideDialogWindow('show_list');
w.setTitle('Other active tasks affecting this Configuration Item');
w.setPreference('table', 'task_list');
w.setPreference('sysparm_view', 'default');
w.setPreference('sysparm_query', "active=true^sys_id!=" + g_form.getUniqueValue() + "^SUBQUERYsys_id,task,task_ci^ci_item=" + gr.ci_item + "^ENDSUBQUERY^GROUPBYsys_class_name");
w.render();
}

If you’ve set up the UI Action correctly, you should now be able to right-click a row in the ‘Affected CIs’ related list and display a dialog showing open tasks for the CI by clicking the ‘Show Related Tasks’ option.

CI Context UI Action - Show Tasks

The post CI UI Macro Actions for the Affected CIs List appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/cmdb/show-bsm-ci-map-affected-cis-related-list/feed/ 4
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