Field script use cases
Summarize
Summary of Field script use cases
This content provides practical examples of client-side and server-side scripting techniques to customize fields within ServiceNow forms and tables. These scripts enable automated field population, input sanitization, UI enhancements, field behavior control, date/time manipulation, and timer toggling. Note that these customizations are developed for specific instances and are not officially supported by Now Support, so thorough testing is essential before deployment.
Show less
Key Use Cases and Practical Implementations
- Automatically Populate a Field: Using an onChange client script on the Incident table’s Subcategory field, a matching Short Description can be auto-filled by querying a custom lookup table. This streamlines data entry by reducing manual input.
- Disable HTML Tags in Descriptions: Server-side scripting replaces potentially unsafe HTML tags (e.g., <script>) in Description and Short Description fields with non-executing text to enhance security and prevent script injection.
- Trim Leading and Trailing Spaces: Server-side scripts clean up user data by removing unwanted spaces from FirstName and LastName fields in the sysuser table, improving data consistency.
- Make a Field Label Flash: A client script example shows how to highlight a field label temporarily by flashing it in a specified color and duration, improving visibility of key fields.
- Make a Field Label Bold: Client scripts can change the font weight of a field label (e.g., Short Description on Incident) to bold, enhancing emphasis in the UI.
- Make Fields Read-Only: On the Incident table, client scripts can lock fields such as Incident State, Impact, Urgency, Priority, Configuration Item, and Assigned To based on certain conditions, and hide reference lookup icons for better form control.
- Set Current Date/Time in Fields: Using GlideAjax in client scripts combined with a server-side Script Include, you can accurately set date/time fields with current values, correctly handling format and timezone issues.
- Toggle Timer Field by Field Name: Client scripts can programmatically start and stop timer fields by simulating button clicks, which helps automate tracking of time-based fields.
- Modify GlideDateTime Field Values: Server-side GlideDateTime API methods allow adding or subtracting time intervals (seconds, days, weeks, months, years) to date/time fields, supporting complex date calculations and adjustments within scripts.
Why This Matters
These script use cases empower ServiceNow customers to tailor form behavior, enhance data quality, improve user experience, and automate routine tasks. Proper application of these scripts can lead to more efficient incident handling, standardized data, and improved interface responsiveness.
Since these scripts are provided as examples and not officially supported, customers should carefully test and adapt them to their unique environments to ensure reliability and compliance with internal policies.
Common use cases for field customization scripts.
For more information, see Server API reference.
Automatically populate a field
The following example shows how to use a client script to auto-fill a Short Description based on the selected Subcategory.
In this case, if the table has a record with Subcategory = Password and Short Description = Password Reset. When the user selects the Subcategory of Password on the Incident form, a client script looks up the matching record and sets Short Description equal to Password Reset.
- Type = onChange
- Table name = incident
- Field name = Subcategory
function onChange(control, oldValue, newValue, isLoading){
if(isLoading){return;}
var newrec = gel('sys_row');
//Check if new record
if (newrec.value == -1) {
var lookup = new GlideRecord('u_short_desc_lookup');
lookup.addQuery('u_subcategory', g_form.getValue('subcategory'));
lookup.query();
var temp; //temp var - reusable
if(lookup.next()){
temp = lookup.u_short_description;
if(null != temp) {
//Set the form value from lookup if there is a lookup value
g_form.setValue('short_description', temp);
} else {
g_form.setValue('short_description',"");
}
} else {
//If a lookup record does not exist based on lookup.addQuery
//Then set to UNDEFINED or NULL depending on type
g_form.setValue('short_description',"");
}
}
}Disable HTML tags in descriptions
doit();
function doit(){
var desc = current.description.toString();
var shdesc = current.short_description.toString();
if(desc.indexOf('script>')>-1|| shdesc.indexOf('script>')>-1){
desc = desc.replace(/<script>/g,"(script)");
current.description = desc.replace(/<\/script>/g,"(\/script)");
shdesc = shdesc.replace(/<script>/g,"(script)");
current.short_description = shdesc.replace(/<\/script>/g,"(\/script)");}
}Eliminate leading and trailing spaces in fields
doit();
function doit(){
var now_GR =new GlideRecord('sys_user');
gr.query();
while(gr.next()){
if((gr.first_name.toString().length!= gr.first_name.toString().trim().length)||(gr.last_name.toString().length!= gr.last_name.toString().trim().length)){
gr.first_name= gr.first_name.toString().trim();
gr.last_name= gr.last_name.toString().trim();
gr.autoSysFields(false);
gr.update();}}
}Make a field label flash
g_form.flash("incident.number","#FFFACD",0);- tablename.fieldname
- RGB color or acceptable CSS color like "blue" or "tomato"
- Integer that determines how long the label flashes:
- 2 for a 1-second flash
- 0 for a 2-second flash
- -2 for a 3-second flash
- -4 for a 4-second flash
Make a field label bold
function onLoad(){
var l = g_form.getLabel('incident.short_description');
l.style.fontWeight = 'bold';}Make fields read-only
- Incident state
- Impact
- Urgency
- Priority
- Configuration item
- Assigned to
function onLoad(){
var incidentState = g_form.getValue('incident_state');
if( incidentState == '6'|| incidentState == '7'){
g_form.setReadonly('incident_state',true);
g_form.setReadonly('impact',true);
g_form.setReadonly('urgency',true);
g_form.setReadonly('priority',true);
g_form.setReadonly('cmdb_ci',true);
g_form.setReadonly('assigned_to',true);}}Set current date/time in field
You can set date and time values in client scripts and script includes.
- Client script
- You can use the following two lines to set the current date and time in a date/time
field. This approach bypasses the problem of getting the value into the proper format
and proper time zone.
var ajax = new GlideAjax('MyDateTimeAjax'); ajax.addParam('sysparm_name','nowDateTime'); ajax.getXML(function(){ g_form.setValue('put your field name here', ajax.getAnswer());}); - System script include
// Be sure the Glide AJAX enabled option is checked var MyDateTimeAjax = Class.create(); MyDateTimeAjax.prototype = Object.extendsObject(AbstractAjaxProcessor,{ nowDateTime:function(){ return gs.nowDateTime();}});
Toggle the timer field by field name
function toggleTimerByFieldName(fieldName){
//Step 1: Find the timer object
//timeObjectName: the timer objects name as it would normally be referenced
//timeObjectHidden: the hidden input node in the field td
//timeObjectParent: the parent td node containing the field and it's constituent nodes
//timeObjectFields: anchor tag with onclick to stop timer
var timeObjectName = fieldName;
var timeObjectHidden = gel(timeObjectName);
//Step 2: simulate click stop button
var timeObjectParent;
var timeObjectFields;
//verify that we got the correct object
if(timeObjectHidden.type=="hidden"){
//Get Parent td node
timeObjectParent = timeObjectHidden.parentNode;
//Get input fields
timeObjectFields = timeObjectParent.getElementsByTagName("input");
//simulate click of stop button
var timerTestString ="paused";
var timerImg;
//loop through input objects looking for the pause timer object
for(var elIt=0; elIt < timeObjectFields.length; elIt++){
if(timeObjectFields[elIt].id.match(timerTestString)){
if(timeObjectFields[elIt].value=="false"){
timeObjectFields[elIt].value="true";
timerImg = timeObjectParent.getElementsByTagName("img")[0];
timerImg.src="images/timer_start.gifx";}
elseif(timeObjectFields[elIt].value=="true"){
timeObjectFields[elIt].value="false";
timerImg = timeObjectParent.getElementsByTagName("img")[0];
timerImg.src="images/timer_stop.gifx";}}}}}Modify GlideDateTime field values
//You first need a GlideDateTime object
//this can be from instantiating a new object "var gdt = new GlideDateTime()"
//or getting the object from a GlideDateTime field
//getting the field value (for example: var gdt = current.start_date) only returns the string value, not the object
//to get the object use var gdt = current.start_date.getGlideObject(); (GlideElement)
//now gdt is a GlideDateTime object
var gdt = current.start_date.getGlideObject();
//All methods can use negative values to subtract intervals
//add 1 hour (60 mins * 60 secs)
gdt.addSeconds(3600);
//add 1 day
gdt.addDaysLocalTime(1);
//subtract 1 day
gdt.addDaysLocalTime(-1);
//add 3 weeks
gdt.addWeeksLocalTime(3);
//subtract 6 months
gdt.addMonthsLocalTime(-6);
//add 1 year, representing the date and time using the UTC timezone instead of the local user's timezone.
gdt.addYearsUTC(1);
//set the value of the GlideDateTime object to the current session timezone/format
GlideSession.get().setTimeZoneName('US/Eastern');
gdt.setDisplayValue('2018-2-28 00:00:00');
gs.info('In ' + GlideSession.get().getTimeZoneName() + ": " + gdt.getDisplayValue());See also: