UI scripts Archives - ServiceNow Guru https://servicenowguru.com/tag/ui-scripts/ ServiceNow Consulting Scripting Administration Development Wed, 03 Jul 2024 18:23:43 +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 UI scripts Archives - ServiceNow Guru https://servicenowguru.com/tag/ui-scripts/ 32 32 Service Portal and DatePicker Field https://servicenowguru.com/service-portal/service-portal-datepicker-field/ Wed, 03 Jul 2024 18:23:43 +0000 https://servicenowguru.com/?p=15498 In the previous article, when creating the form with the fields that will be used when importing the Excel file, I chose to use a library that provides many different configuration options: Bootstrap Datepicker In the same way we did with the SheetJS library, the first thing we need to do is download the necessary

The post Service Portal and DatePicker Field appeared first on ServiceNow Guru.

]]>
In the previous article, when creating the form with the fields that will be used when importing the Excel file, I chose to use a library that provides many different configuration options: Bootstrap Datepicker

In the same way we did with the SheetJS library, the first thing we need to do is download the necessary files. On GitHub you will find the link to download the “.js” and “.css” in cdnjs and some online demos.

The library’s documentation is very complete and contains several styling options and methods to use.

After downloading the files, create a dependency on the widget that will use the library:

 

 

After creating the dependency, the library will be ready to be used. We just need to start it and configure it according to our needs (in my case I just wanted the MM/YYYY information)

HTML

<!-- Field Period -->
<label class="control-label" for="monthYear">Month/Year</label>
<input id="monthYear" name="monthYear" class="form-control" placeholder="MM/YYYY" ng-model="c.model.monthYear.displayValue" readonly>

Link Function

$(document).ready(function(){

    setTimeout(function(){
            
        $('#monthYear').datepicker({
            format: "mm/yyyy",
            startDate: "-22m",				
            endDate: "-1m",
            startView: 1,
            minViewMode: 1,
            maxViewMode: 2,
            autoclose: true,
            toggleActive: true,
            language: "pt-BR"
        });

    },300);

});
The above script must be used in the “Link Function” as it is not a good practice to use jQuery in the Client Script.

After initialization and configuration as desired, it will be ready for use:

The post Service Portal and DatePicker Field appeared first on ServiceNow Guru.

]]>
Load Excel files to ServiceNow using Portal https://servicenowguru.com/service-portal/load-excel-files-to-servicenow-using-portal/ https://servicenowguru.com/service-portal/load-excel-files-to-servicenow-using-portal/#comments Tue, 28 May 2024 16:28:39 +0000 https://servicenowguru.com/?p=15379 As platform administrators we know that there are many ways to import an Excel file to ServiceNow. But what if you need to provide your client a way to load data without accessing one of these tools? When we talk about importing data to ServiceNow, the SheetJS library can be extremely useful in helping us

The post Load Excel files to ServiceNow using Portal appeared first on ServiceNow Guru.

]]>
As platform administrators we know that there are many ways to import an Excel file to ServiceNow. But what if you need to provide your client a way to load data without accessing one of these tools?

When we talk about importing data to ServiceNow, the SheetJS library can be extremely useful in helping us with this process (manipulating spreadsheets in the browser). Developers can create custom integrations to transfer data between ServiceNow and other applications. For example, a developer might build a custom integration that allows data to be imported from an external Excel spreadsheet into ServiceNow.

SheetJS: https://git.sheetjs.com/sheetjs/sheetjs

Business Use Case

In this article, we will use as an example an outsourced company that needs to import the hours worked by its employees to the platform so that these hours can be processed and paid. All records must be associated with a department. All necessary validations will be described in a future article. At this point we will only talk about importing the data.

The person in charge of the company will have to access the portal and upload an Excel file with the employees hours following the following model:

 

exemple table

 

 

The Solution

The first thing we need is to import the standalone version of SheetJS into ServiceNow. Open the link to the xlsx.full.min.js file and copy all the code. After that, we will create a UI Script to import this file into the platform:

 

UI Script

 

The next step is to associate this script with the portal. To do this, open the theme used, go to the ‘JS Includes’ related list and click on ‘New’. In the ‘UI Script’ field, select the script created in the previous step and click ‘Submit.’

 

JS Include

 

Now, let’s start developing the widget that will import the data. We will start by creating the form where the file will be uploaded. Using Bootstrap’s grid system and some CSS changes (which we won’t cover in this article) we have the following result:

Widget
Widget Component: HTML Template
Script:

<form ng-submit="c.submitFile()" name="form" id="my-form">
  <fieldset class="form-row">
    <div class="form-group col-md-3">
      <!-- Field Period -->
      <label class="control-label" for="monthYear">Month/Year</label>
    </div>
    <div class="form-group col-md-3">
      <!-- Field Department -->
      <label for="department">Department</label>
    </div>
    <div class="form-group col-md-3">
      <!-- Input file -->
      <label for="department">Attach File</label>
    </div>
    <div class="form-group col-md-3">
      <!-- Buttom submit -->
      <button
        type="submit"
        id="submit"
        class="btn submit-btn btn-block btn-primary"
      >
        Submit
      </button>
    </div>
  </fieldset>
</form>

This is the code preview:

 

 

Now let’s insert the fields. The final HTML should look like this:

Widget
Widget Component: HTML Template
Script:

<form ng-submit="c.submitFile()" name="form" id="my-form">

  <fieldset class="form-row">

    <div class="form-group col-md-3">
      
      <!-- Field Period -->
      <label class="control-label" for="monthYear">Month/Year</label>
      <input id="monthYear" name="monthYear" placeholder="MM/YYYY" ng-model="c.model.monthYear.displayValue"
             class="form-control" readonly>

    </div>
    
    <div class="form-group col-md-3">
      
      <!-- Field Department -->
      <label for="department">Department</label>
      <sn-record-picker name="department"
                        field="c.model.department"
                        table="c.recordPicker.table"
                        default-query="c.recordPicker.query"
                        display-field="c.recordPicker.display.field"
                        display-fields="c.recordPicker.display.fields"
                        value-field="c.recordPicker.value"
                        search-fields="c.recordPicker.search"
                        page-size="c.recordPicker.size"
                        >
      </sn-record-picker>
      
    </div>
    
    <div class="form-group col-md-3">
      
      <!-- Input file -->
      <label for="attachment" class="btn btn-block btn-primary" ng-hide="c.haveAttachment">
        <span class="glyphicon glyphicon-paperclip"></span> Attach File
      </label>
      
      <div ng-show="c.haveAttachment" class="file-attached">
        {{c.fileName}} <a id="clear" href="" ng-click="c.removeAttachment()">
        <span class="glyphicon glyphicon-remove"></span></a>
      </div>
      
      <input type="file" name="attachment" id="attachment" accept=".xls,.xlsx" 
             onchange="angular.element(this).scope().readAttachment(angular.element(this)[0].files[0])"  
             >
    </div>
    
    <div class="form-group col-md-3">
      
      <!-- Buttom submit -->
      <button type="submit" id="submit" class="btn submit-btn btn-block btn-primary">Submit</button>
      
    </div>
    
  </fieldset>
  
</form>

Regarding HTML, I will leave two points for the next articles:

  • The field Department will be created using the snRecordPicker directive:

 

Now we have the form with all its components:

Now that we have our HTML built, let’s move on to the Client Script and create the functions that will be used. This will be the most important part of the article because it is here that we will read the file. Once the file has been selected using the button on the form, we need a script to read, process, and insert the data into the table (for this article we will not perform any type of validation on the data).

Widget
Widget Component: Client Script
Script:

api.controller=function($scope, spUtil) {
    
  var c = this;

    c.model = {};
    
    c.hoursToSubmit = [];
    
    /* 
        read the file
        the function get the attached file as a blob
        https://developer.mozilla.org/en-US/docs/Web/API/Blob
    */
    $scope.readAttachment = function(blob) {

        //check if the file is XLS or XLSX
        var isXLSX = blob.name.endsWith('.xlsx') || blob.name.endsWith('.xls');

        // If not an Excel file the function fails
        if (!isXLSX) {
            spUtil.addErrorMessage("The file must be .xlxs or .xls");
            //c.removeAttachment();
            return;
        }

        c.fileName = blob.name;

        /* star the reader */
        var myReader = new FileReader();

        /* function that will be executed when the reader is called	*/
        myReader.onload = function(e) {

            var data = e.target.result;

            /* get the workbook */
            var workbook = XLSX.read(data, {
                type: "binary"
            });
            var o = {};

            /* get the first sheet name */
            var name = workbook.SheetNames[0];

            /* obtain the JSON object of the sheet and stringify */
            var work_hours = XLSX.utils.sheet_to_json(workbook.Sheets[name], {header: "A"});

            /* remove the first line (columns titles) using Lodash*/
            work_hours = _.drop(work_hours, 1);

            if (work_hours.length == 0) {

                spUtil.addErrorMessage("Nothing to import!");
                //c.removeAttachment();
                return;

            } else {

                /* For this article we will not do any type of validation */
                c.hoursToSubmit = work_hours;
                return;

            }

        }

        /* stars the reader */
        myReader.readAsBinaryString(blob);
    }
    
    c.submitFile = function() {
                
        $scope.server.get({
            action: "insert-hours",
            monthYear: c.model.monthYear,
            department: c.model.department,
            hoursToSubmit: c.hoursToSubmit
        }).then(function(resp) {
            
            spUtil.addInfoMessage("Sucess! Good job!! :)");
            c.hoursToSubmit = [];
            c.model = {};
            //c.removeAttachment();
            
        });
        
    }

};
Widget
Widget Component: Server Script
Script:

(function() {
    
    if(input && input.action == 'insert-hours') {
        
        var grWH = new GlideRecord('x_529701_snguru_worked_hours');
        
        for (var i = 0; i < input.hoursToSubmit.length ; i++) {
            
            grWH.initialize();			
            grWH.setValue('id', input.hoursToSubmit[i]['A'].toString());
            grWH.setValue('name', input.hoursToSubmit[i]['B']);
            grWH.setValue('u_departament', input.department.value);			
            grWH.setValue('period', input.monthYear.displayValue);
            grWH.setValue('u_type', input.hoursToSubmit[i]['C']);
            grWH.setValue('hours', parseInt(input.hoursToSubmit[i]['D']));
            grWH.insert();
            
        }
        
    }

})();

Now our widget is ready to make the magic happen! Fill in the fields, select the file, and click ‘Submit’.

 

 

If everything goes well, the data will be written to the table:

 

 

Conclusion

By leveraging the SheetJS library and custom ServiceNow widgets, we have created a streamlined solution for importing employee work hours from Excel files directly into ServiceNow. This approach eliminates the need for users to access external tools, simplifying the process and enhancing user experience. Such integrations not only save time, but also reduce errors associated with manual data entry, ensuring that the data processing is efficient and accurate.

The post Load Excel files to ServiceNow using Portal appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/service-portal/load-excel-files-to-servicenow-using-portal/feed/ 4
Bringing the Update Set Picker back from the UI14 Gear Menu https://servicenowguru.com/ui-scripts-system-ui/bringing-update-set-picker-ui14-gear-menu/ https://servicenowguru.com/ui-scripts-system-ui/bringing-update-set-picker-ui14-gear-menu/#comments Thu, 28 Aug 2014 15:20:32 +0000 https://servicenowguru.wpengine.com/?p=5410 The ServiceNow Eureka release contains many new features and changes. Among these are some significant changes to the look and feel that are generally a very nice (and needed) improvement over previous versions of ServiceNow. I have heard a few complaints about the way that the Banner Frame has been reorganized though. Instead of having

The post Bringing the Update Set Picker back from the UI14 Gear Menu appeared first on ServiceNow Guru.

]]>
The ServiceNow Eureka release contains many new features and changes. Among these are some significant changes to the look and feel that are generally a very nice (and needed) improvement over previous versions of ServiceNow. I have heard a few complaints about the way that the Banner Frame has been reorganized though. Instead of having the update set, language, and application pickers, etc. available directly, they’ve been moved into a separate menu which is now accessed by clicking a gear icon in the header. While I understand ServiceNow’s reasoning for this – the old header bar was starting to look very dated and cluttered – the update set picker in particular is something that I believe really needs to be visible to admins and developers at all times. In this post I’ll show you a quick workaround you can apply to your system to bring the update set picker back where it belongs!

MoveUpdateSetPicker

The Solution…

There’s no way to get at the back-end code that controls the gear menu popup so our only option is to manipulate the UI using client scripting. Since this is a global issue independent of any specific table or form, we can use a UI script to target the Update Set picker element and move it to a different location on the page. The following script does just that, just make sure to remember to check the ‘Global’ checkbox on the UI script record. Enjoy!

‘MoveUpdateSetPicker’ UI Script
Name: MoveUpdateSetPicker
Global: true
Script:

addLoadEvent(moveUpdateSetPicker);function moveUpdateSetPicker(){
try{
//Only run if UI14
if($('navpage_header_control_button')){
//Fix Fuji styling
$('update_set_picker_select').className = '';
if($('update_set_picker').select('li')[0]){
$('update_set_picker').select('ul')[0].style.marginBottom = "0px";
$('update_set_picker').select('li')[0].className = '';
$('update_set_picker').select('li')[0].style.paddingRight="5px";
$('update_set_picker').select('li')[0].style.listStyleType ="none";
$('update_set_picker').select('li')[0].select('a')[0].style.color ="#FFF";
$('update_set_picker').select('li')[0].select('a')[0].style.border ="none";
$('update_set_picker').select('li')[0].select('a')[1].style.color ="#FFF";
$('update_set_picker').select('li')[0].select('a')[1].style.border ="none";
$('update_set_picker').select('li')[0].select('a')[2].style.color ="#FFF";
$('update_set_picker').select('li')[0].select('a')[2].style.border ="none";
$('update_set_picker_select').style.color ="#000";$$('.btn-icon').each(function(d){
d.style.lineHeight = 'inherit';
});
}
if($('update_set_picker').select('legend')[0]){
$('update_set_picker').select('legend')[0].remove();
}
//Move the update set picker from under the gear icon to the header
$('nav_header_stripe_decorations').insert({
top: $('update_set_picker')
});
//Make sure that UI14 doesn't change styling
$('update_set_picker').id = 'update_set_picker_new';
}
}catch(e){}
}

UpdateSetPicker-Moved

Moving the Home icon…

I’ve had a few people ask about moving the home icon back as well. This one is a bit more difficult because of the lack of a decent ID to target, not to mention the old-style icon. In this case, I think it’s probably easier just to create a new icon in the header. The following code could be placed inside of the ‘if’ statement in the update set picker code above to also add a ‘home’ icon in the header.

//Create a home icon in the header
$('navpage_header_control_button').insert({
before: '<button id="navpage_header_home_button" class="nav_header_button icon-home" style="display: inline; visibility: visible;" title="Home" aria-label="Home"></button>'
});

The post Bringing the Update Set Picker back from the UI14 Gear Menu appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/ui-scripts-system-ui/bringing-update-set-picker-ui14-gear-menu/feed/ 74
Display Messages With UI Notifications https://servicenowguru.com/ui-scripts-system-ui/display-messages-ui-notification/ https://servicenowguru.com/ui-scripts-system-ui/display-messages-ui-notification/#comments Tue, 18 Feb 2014 13:29:41 +0000 https://servicenowguru.wpengine.com/?p=5143 Some time ago we showed you how to refresh the left navigation pane via a script. The server-side solution in that article utilizes ServiceNow’s UINotification object/class. On versions prior to Calgary, this is the Java class Packages.com.glide.ui.UINotification.  There’s another use for UI notifications. In addition to refreshing the left navigator, the object can also be

The post Display Messages With UI Notifications appeared first on ServiceNow Guru.

]]>
Some time ago we showed you how to refresh the left navigation pane via a script. The server-side solution in that article utilizes ServiceNow’s UINotification object/class. On versions prior to Calgary, this is the Java class Packages.com.glide.ui.UINotification

There’s another use for UI notifications. In addition to refreshing the left navigator, the object can also be used to display informational messages. You’ve probably already seen these in your own instance. When you change update sets, the system reminds you by using a UI Notification similar to the one shown below:

Update Set Change

If you’re like me, you may have wondered how these notifications are created. Displaying a custom UI notification is slightly more complex than using the addInfoMessage() method provided by the GlideSystem (server) and GlideForm (client) classes. In return, it gives you some capabilities that aren’t otherwise available. These include options to set fade-in and fade-out effects and the ability to make the notification persistent or to close it after a user-specified interval. If you want to learn more about the various types of notifications available in ServiceNow, check out our UI Info and Error Message Cheat Sheet.

The example below uses the UINotification object to display a list of all fields that have been changed on an incident. I’d like to take credit for this solution, but it was actually my colleague Jim Coyne who did the heavy lifting. I’m most especially indebted to him for compiling the all-important list of option properties that determine how the notification behaves.

As with any undocumented API, ServiceNow could make changes to the UINotification class at any time that might break the functionality we’re describing. Also, ServiceNow Technical Support won’t give you any help if you have trouble with this. Be sure to keep those things in mind if you decide to use custom UI Notifications in your instance.

Creating The Notification

To create the UI Notification and its options, use a global UI Script:

‘Popup UI Notification’ UI Script
Name: Popup UI Notification
Active: true
Global: true
Description: Adds a popup UI Notification to the DOM. Can be called from any server-side script. For an example, see ‘Changed Fields UI Notification’ business rule on the Incident table.
Script:

//Ensure that the CustomEvent object exists
var intervalTest = setInterval(function(){
   if(typeof CustomEvent != 'undefined'){
      clearInterval(intervalTest);
      setCustomEvents();
   }
},500);

//Add the UI Notification to the DOM using the CustomEvent object
function setCustomEvents(){
   //Set the name of the notification
   var notifName = "demo_notification";
   CustomEvent.observe('glide:ui_notification.' + notifName,
   function(notification){
      var msgText = notification.getAttribute('text1'); //get the message text from the attribute passed in by the business rule
      var options = {}; //create a new object to store all of the message attributes.
      options.text = "<span style='color:red;'>" + msgText + "</span>";
      options.sticky = true;
      options.closeDelay = 5000;
      options.fadeIn = 500;
      options.fadeOut = 500;
      new NotificationMessage(options); //display the UI Notification
   });
}

The CustomEvent object takes two arguments:

  1. The ‘glide:ui_notification.‘ object. This object includes a mandatory property that defines its name. In our example we’ve used a variable to store the name, but it could also be added to the object as an explicit value. In that case, it would be written ‘glide:ui_notification.demo_notification’ (including the quotes).
  2. A function that defines the notification’s contents and display options. The display options determine how the notification will behave. The options should be defined as properties in their own options object within the function. Available options properties include:
    text: Required. The text of the message. You can include rich text formatting via standard HTML tags.
    sticky: Optional. If true, the notification persists until the user closes it by clicking the [x] icon. If false or omitted, the notification automatically closes after the specified closeDelay.
    closeDelay: Optional. Automatically closes the message after this number of milliseconds. If omitted, the message closes after about three seconds. If the sticky property is true, this option is ignored.
    fadeIn: Optional: Sets the fade-in time for the notification in milliseconds
    fadeOut: Optional: Sets the fade-out time for the notification in milliseconds if the sticky property is false/omitted. If the sticky property is true, this option is ignored.
Note that if fadeIn, fadeOut and closeDelay intervals are specified, they are additive. That is, the notification will be displayed for the total amount of time specified in all three properties.

The function uses the getAttribute() method to retrieve the information passed in from the server-side script which triggers the notification. If multiple attributes have been set in the server-side script, the UI Script will need additional getAttribute() method calls to retrieve each one.

Displaying the Notification

To display the notification, we simply instantiate, (create a new instance of) the UINotification object in a Business Rule (it may work in other server-side scripts but I haven’t tested that). For our example we’ll use a business rule that runs after the incident has been updated. Our script borrows code from a previous post about checking for modified fields on forms or records.

‘Changed Fields UI Notification’ Business Rule
Name: Changed Fields UI Notification
Table: Incident [incident] Active: true
When: after
Update: true
Script:

//First, get an ArrayList of all fields changed on the record
if (typeof GlideScriptRecordUtil != 'undefined') {
   var gru = GlideScriptRecordUtil.get(current);
} else {
   var gru = Packages.com.glide.script.GlideRecordUtil.get(current);
}

var changedFields = gru.getChangedFields(); //Get changed fields with friendly names

//Next, pass the values into the UI Notification we defined in the UI Script
var notification;
if(typeof UINotification != 'undefined') {
   notification = new UINotification('demo_notification'); //Calgary and later releases use the UINotification object call
} else {
   notification = new Packages.com.glide.ui.UINotification('demo_notification'); //For pre-Calgary releases, use the Java Package call
}

//create the message to be displayed
var messageText = gs.getUser().getDisplayName();
messageText += ' modified the following fields on : ';
messageText += current.number;

/*
Assign the message text to the 'text1' attribute. Additional attributes can be passed into the UI notification. Just be sure each one is accounted for in the UI Script via getAttribute() method calls.
*/
notification.setAttribute('text1', messageText + changedFields);
notification.send();

The key items in the business rule’s script are:

  • The new UINotification object call that specifies the object we defined in the UI Script (‘demo_notification’)
  • The setAttribute() method that passes specific information into the notification
  • The send() method that triggers the actual display of the notification.

To see the notification, open any Incident and modify one or more fields, then Save or Update it.

Incident field changes

Once the UI Script is defined, it can be reused as many times as needed. Just call it from any business rule and pass information to it using the setAttribute() method.

The post Display Messages With UI Notifications appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/ui-scripts-system-ui/display-messages-ui-notification/feed/ 19
Collapse Navigation and Header Frames via Script https://servicenowguru.com/ui-scripts-system-ui/collapse-navigation-header-frames-script/ https://servicenowguru.com/ui-scripts-system-ui/collapse-navigation-header-frames-script/#comments Tue, 06 Nov 2012 14:56:41 +0000 https://servicenowguru.wpengine.com/?p=4653 Every once in a while I come across some script functions that might be useful given the right requirement. This article is one of those cases. In the post below I’ll show you how you can leverage some built-in client-side functions to show and hide the navigation and header frames in ServiceNow. Navigation Frame The

The post Collapse Navigation and Header Frames via Script appeared first on ServiceNow Guru.

]]>
Every once in a while I come across some script functions that might be useful given the right requirement. This article is one of those cases. In the post below I’ll show you how you can leverage some built-in client-side functions to show and hide the navigation and header frames in ServiceNow.

Navigation/Banner Frames

Navigation Frame

The navigation frame can be hidden, shown, or toggled using the following functions…

//Hide the left nav
hideNav();

//Show the left nav
showNav();

//Toggle the left nav
toggleNav();

Here’s an example global UI script that you could use to hide the left nav from end-users

‘HideLeftNav’ UI Script
Name: ‘HideLeftNav’
Global: true
Description: Hide the left nav for end users
Script:

addLoadEvent(hideLeftNav);function hideLeftNav(){
try{
//If the user has no roles
if(!g_user.hasRoles()){
//Hide the left nav
hideNav();
//Hide the toggle image (optional)
//$('navToggleImage').hide();
}
}catch(e){}
}

 

Header/Banner Frame

The banner doesn’t have as many functions available to it, but you can still toggle the banner like this…

//Toggle the header/banner
toggleBanner();

The post Collapse Navigation and Header Frames via Script appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/ui-scripts-system-ui/collapse-navigation-header-frames-script/feed/ 2
Modifying the Label of Form Fields With Client Scripts https://servicenowguru.com/ui-scripts-system-ui/modifying-label-form-fields-client-scripts/ https://servicenowguru.com/ui-scripts-system-ui/modifying-label-form-fields-client-scripts/#comments Mon, 10 Oct 2011 16:47:32 +0000 https://servicenowguru.wpengine.com/?p=4067 Please note that with the introduction of the Service Portal, many client-side scripting methods have been deprecated. The solution described in this article can now be accomplished using the ‘setLabel()’ method. To ensure that you are compliant with the latest functionality in ServiceNow such as the Service Portal, be sure to use the methods described

The post Modifying the Label of Form Fields With Client Scripts appeared first on ServiceNow Guru.

]]>
Please note that with the introduction of the Service Portal, many client-side scripting methods have been deprecated. The solution described in this article can now be accomplished using the ‘setLabel()‘ method. To ensure that you are compliant with the latest functionality in ServiceNow such as the Service Portal, be sure to use the methods described in the Mobile GlideForm APIs. Just make sure you set the ‘UI type’ field on the client script form to ‘Both‘.

Here’s a quick tip for a Monday. This post comes in response to a question on the ServiceNow forums asking if it is possible to change the label of a field dynamically based on some record criteria (such as record type). It is possible, and this post will show you how it can be done.
Dynamic Field Label

First, you should know that you can right-click any field and personalize the label for that field. For extended tables (such as incident) you can override the label for a higher-level table (such as task) just by changing the table name on the label record and doing an ‘Insert’ rather than a save. The question that I’ll address in this post is different than both of those scenarios though. What if you have a label that you want to change based on the user viewing the record? What if you need to change the label based on some criteria unique to that table (such as change type or incident priority)? In that case, you can’t simply modify the label record because you’ve got a narrower scope within that table that you need to work with.

The answer is client scripting. With a client script you can target any field on the form and modify its label. I’ve created a ‘changeFieldLabel’ function for this purpose. The function takes 4 possible parameters to allow for changing of the label text, color, and font weight.

Here’s an example that you could use in an ‘onLoad’ client script to change the ‘Description’ field label on a Change request form…

function onLoad() {
//Change the description label to 'My New Label' with bold red text
changeFieldLabel('description', 'My New Label', 'red', 'bold');
}

function changeFieldLabel(field, label, color, weight){
try{
var labelElement = $('label.' + g_form.getControl(field).id);
labelElement.select('.label-text').each(function(elmt) {
elmt.innerHTML = label + ':';
if(color)
elmt.style.color = color;
if(weight)
elmt.style.fontWeight = weight;
});
}catch(e){};
}

Of course, this is much more accessible if you include it in a global UI script. If you’re going to use this a lot I recommend setting up a global UI script with the following function…

function changeFieldLabel(field, label, color, weight){
try{
var labelElement = $('label.' + g_form.getControl(field).id);
labelElement.select('.label-text').each(function(elmt) {
elmt.innerHTML = label + ':';
if(color)
elmt.style.color = color;
if(weight)
elmt.style.fontWeight = weight;
});
}catch(e){};
}

Then you can invoke the function from any form with a single line.

If I wanted to change the label of the ‘description’ field to ‘My New Label’ I could do it like this…

changeFieldLabel('description', 'My New Label');

If I wanted to change the label to a bold green color I could do it like this…

changeFieldLabel('description', 'My New Label', 'green', 'bold');

Changing the label of a catalog variable

The principles described above can also be applied to catalog variables using catalog client scripts. The primary difference is in the way the elements need to be selected from the DOM. Here’s an example script…

function onLoad() {
//Change the description label to 'My New Label' with bold red text
changeFieldLabel('description', 'My New Label', 'red', 'bold');
}

function changeFieldLabel(field, label, color, weight){
try{
var labelElement = $('label_' + g_form.getControl(field).id);
labelElement.select('.sn-tooltip-basic').each(function(elmt) {
elmt.innerHTML = label;
if(color)
elmt.style.color = color;
if(weight)
elmt.style.fontWeight = weight;
});
}catch(e){};
}

The post Modifying the Label of Form Fields With Client Scripts appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/ui-scripts-system-ui/modifying-label-form-fields-client-scripts/feed/ 69
Highlight Selected Navigation Module https://servicenowguru.com/ui-scripts-system-ui/highlight-selected-navigation-module/ https://servicenowguru.com/ui-scripts-system-ui/highlight-selected-navigation-module/#comments Wed, 14 Sep 2011 14:05:52 +0000 https://servicenowguru.wpengine.com/?p=4000 I received a client request last night asking if there was any way to provide some sort of additional highlighting to the currently-selected module in the left navigation. You’re probably already aware that when you click on a link in the left nav that link changes to a bold text. The client wanted to add

The post Highlight Selected Navigation Module appeared first on ServiceNow Guru.

]]>
I received a client request last night asking if there was any way to provide some sort of additional highlighting to the currently-selected module in the left navigation. You’re probably already aware that when you click on a link in the left nav that link changes to a bold text. The client wanted to add a background highlight color in addition to the bolded text so that the selected module would be easier to see. The end result of this customization looks something like this…


This customization obviously isn’t for everybody, but I think it does demonstrate a good use of UI scripts. The script below needs to be set up as a Global UI script so that it will run throughout the user session. Within the script I check to see if the navigation pane is being loaded or not so we can cut down on a lot of the unnecessary code when the main frame is loading content. If the script finds the navigation pane it attaches an event to each menu item. This event is triggered when the item is clicked and it adds the highlight color to that item. In addition, it removes the highlight color from the previously-selected menu item.

You can change the highlight color by modifying the ‘lightskyblue’ text below to whatever color you want!

‘AddNavMenuHighlight’ UI script
Name: AddNavMenuHighlight
Global: True
Description: Adds a highlight color to the background of the last-selected module in the left navigation.
Script:

var lastAppLinkColor;
var menuCheckCount = 0;

addLoadEvent( function() {
   //Attach an event to the click of any nav menu item
   var menuCheckInterval = setInterval(function(){checkMenu()},1000);
   function checkMenu(){
      try{
         if(window.frames[1]){
            var menuItems = window.frames[1].document.getElementsByTagName('a');
            if (menuItems.length != 0 || menuCheckCount > 10) {
               clearInterval(menuCheckInterval);
               setHighlight(menuItems);
            }
            else{
               menuCheckCount++;
            }
         }
      }catch(e){}
   }
   function setHighlight(menuItems){
      for (i=0; i < menuItems.length; i++) {
         if(menuItems[i].className == 'menu'){
            Event.observe(menuItems[i], 'click', function(event) {
               //Remove the highlight from the previously-highlighted menu item
               if (lastAppLinkColor) {
                  lastAppLinkColor.style.backgroundColor = "";
               }
               //Get the parent table row of the link clicked
               var elt = Event.findElement(event, 'div'); //If UI11 target 'tr' instead of 'div'
               if (elt != document) {
                  //Add the highlight color
                  $(elt).style.backgroundColor = "lightskyblue";
                  lastAppLinkColor = elt;
               }
            });
         }
      }
   }
});

The post Highlight Selected Navigation Module appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/ui-scripts-system-ui/highlight-selected-navigation-module/feed/ 32
Animate ServiceNow with jQuery and Prototype Effects! https://servicenowguru.com/system-ui/jquery-prototype-animation-effects/ https://servicenowguru.com/system-ui/jquery-prototype-animation-effects/#comments Tue, 09 Aug 2011 13:11:35 +0000 https://servicenowguru.wpengine.com/?p=3667 A while ago, I was trying to figure out how I could add some javascript animations and effects to a ServiceNow instance. What I really wanted was something like the jQuery Effects API but I didn’t want to have to incorporate a separate API and deal with the loading the bulk of jQuery everywhere in

The post Animate ServiceNow with jQuery and Prototype Effects! appeared first on ServiceNow Guru.

]]>
A while ago, I was trying to figure out how I could add some javascript animations and effects to a ServiceNow instance. What I really wanted was something like the jQuery Effects API but I didn’t want to have to incorporate a separate API and deal with the loading the bulk of jQuery everywhere in the instance. I knew that ServiceNow provided some limited collapse/expand effects but I was hoping for a little bit more.

I’m happy to report that I found it! Somebody smarter than me decided to convert the jQuery effects library for use with Prototype (which ships with ServiceNow) and incorporate those effects and animations directly in ServiceNow.

ServiceNow Prototype Effects

This effects collection includes the ability to animate, slide, toggle, and fade most dom elements and works just like the jQuery library. Best of all, it’s all laid out in a simple UI page directly in your ServiceNow instance! You can view this by navigating to the following URL…

https://demo.service-now.com/prototype_effects.do

So far, I’ve found this to be useful in some custom UI pages and a collapsible CMS menu I built. I’m planning on posting the collapsible menu solution sometime soon. Post a comment here if you come up with a cool solution using some of these effects!

The post Animate ServiceNow with jQuery and Prototype Effects! appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/system-ui/jquery-prototype-animation-effects/feed/ 10
Single Click Impersonation Return https://servicenowguru.com/system-definition/single-click-impersonation-return/ https://servicenowguru.com/system-definition/single-click-impersonation-return/#comments Mon, 18 Jul 2011 13:42:55 +0000 https://servicenowguru.wpengine.com/?p=3908 I noticed an enhancement request from Matt Beran on Twitter over the weekend. The enhancement request was for an easier way to end a user impersonation session. Currently, you have to click the impersonation icon, wait for the dialog to appear, and select your original account to end an impersonation session. While this might not

The post Single Click Impersonation Return appeared first on ServiceNow Guru.

]]>
I noticed an enhancement request from Matt Beran on Twitter over the weekend. The enhancement request was for an easier way to end a user impersonation session. Currently, you have to click the impersonation icon, wait for the dialog to appear, and select your original account to end an impersonation session. While this might not be a huge issue for some people, it can get kind of old if you’re trying to quickly do a lot of testing or troubleshooting that requires frequent user impersonations. This post explains how you can create a UI script to add a button that will end impersonation and return you to your original session in a single click!

One-Click Unimpersonate Button

This solution leverages some ideas I presented in a previous post about impersonating users from any record in the system. Check it out if you’re interested in other nice ways to make the user-impersonation process more useful and convenient.

The simplest way to add this functionality is to create a clickable image that will end the user impersonation and add it to the page header. The challenge is to do this without hacking the out-of-box UI macro and breaking upgrades to the impersonate functionality in the future. Fortunately this can all be accomplished with the creation of a global UI script! Here’s how you can set it up.

‘AddUnimpersonate Button’ UI script
Name: AddUnimpersonate Button
Global: True
Description: Add a button during user impersonations to allow one-click return to original session.
Script:

addLoadEvent(addUnimpersonateButton);

function addUnimpersonateButton(){
	try{
		//Show un-impersonate icon if a user is being impersonated
		if($('impersonating_toggle_id').value != ''){
			//Insert the clickable icon in the dom
			$('impersonate_span').insert(
				'<span id="unimpersonate_span" class="icon-power" style="padding-left:5px; cursor:pointer;cursor:hand; font-size: 20px; visibility: visible" title="End impersonation" onclick="unimpersonateMe();" />'
			);
		}
	}catch(e){}
}

function unimpersonateMe(){
	//Return the user to their original session
	top.location.href = 'ui_page_process.do?sys_id=b071b5dc0a0a0a7900846d21db8e4db6&sys_user='+ $('impersonating_toggle_id').value;
}

The post Single Click Impersonation Return appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/system-definition/single-click-impersonation-return/feed/ 36
Adding a Logo to Public Report Pages https://servicenowguru.com/ui-scripts-system-ui/adding-logo-public-report-pages/ https://servicenowguru.com/ui-scripts-system-ui/adding-logo-public-report-pages/#comments Wed, 30 Mar 2011 15:24:26 +0000 https://servicenowguru.wpengine.com/?p=3530 One of the features of the Service-now reporting system is the ability to publish a report so that unauthenticated users can view certain reporting information about your environment. When a report is published, the system gives you a public URL that you can make available to your users. Users viewing a published report will see

The post Adding a Logo to Public Report Pages appeared first on ServiceNow Guru.

]]>
One of the features of the Service-now reporting system is the ability to publish a report so that unauthenticated users can view certain reporting information about your environment. When a report is published, the system gives you a public URL that you can make available to your users. Users viewing a published report will see the report, but no additional information about your Service-now instance or company. In some cases, it may be desirable to add some identifying information to these published reports (like a company logo). In this article I’ll show you how that can be done.

Public Report-Logo

Here’s a screenshot showing the problem we’re trying to solve. We’ve got a nice published report that we would like to add a logo to…
Public Report

The first option is to make use of the built-in navigation frames in Service-now

When you publish a report, the system shows you a URL like this…

https://demo.service-now.com/sys_report_display.do?sysparm_report_id=a19bd425c611227b00232a5dc90c99a2

A simple change to the URL (the addition of ‘nav_to.do?uri=’) adds navigation frames (and your instance logo) to the report.

https://demo.service-now.com/nav_to.do?uri=sys_report_display.do?sysparm_report_id=a19bd425c611227b00232a5dc90c99a2

By modifying the URL to include the navigation frames you can display your report like this…
Public Report-Logo Navigation

The only problems with this method are that you can’t really control how that URL gets generated so you can’t always ensure that users will know about this trick, and the navigation frames won’t be included in the printable version so your logo will only be available when viewed in a browser.

The other option is a simple UI script to manipulate the report page itself

Usually when you’re dealing with non-standard forms in Service-now (like the report view page) the code can be found in a UI page or UI macro. In the case of the report pages however, the code is actually stored in back-end XML files. This makes it a bit harder to manipulate. I’ve written previously about a functionality I created to limit the reportable tables in Service-now. The technique I used to accomplish that modification is the same technique I’ll use here. It involves the creation of a global UI script that identifies when it is running on the report page and manipulates the page accordingly.

Here are the settings for the UI script you’ll need to create…

‘Add Public Report Header’ UI Script
Name: Add Public Report Header
Global: True
Script:

addLoadEvent(addPublicReportHeader);

function addPublicReportHeader(){
   if($('partialPage:theReport') && !$('reportform_control')){
      $('partialPage:theReport').insert({
         top: '<img src="http://www.sncguru.com/logo.png" class="chart"></img>'
      });
   }
}

The global UI script uses a couple of dom elements to identify whether or not it is running on the public report page. If it is, it simply adds the logo image. You can customize the ‘sncguru’ portion of the script to add the logo of your choosing. When you’re done, all of your public reports will display your logo at the top of the page like this…
Public Report-Logo

The post Adding a Logo to Public Report Pages appeared first on ServiceNow Guru.

]]>
https://servicenowguru.com/ui-scripts-system-ui/adding-logo-public-report-pages/feed/ 12