Please use docs.servicenow.com for the latest documentation.

This site is for reference purposes only and may not be accurate for the latest ServiceNow version

Useful Form Scripts

From Wiki Archive
Jump to: navigation, search

This is a searchable version of the Useful Form Customization Scripts. For an easy-to-navigate version, visit the Useful Scripts portal.



Note
Note: This article applies to Fuji and earlier releases. For more current information, see Glide Class Overview at http://docs.servicenow.com

The ServiceNow Wiki is no longer being updated. Visit http://docs.servicenow.com for the latest product documentation.

Overview

GlideForm.js is the Javascript class used to customize forms.

  • g_form is a global object in the GlideForm class.
  • GlideForm.js and g_form are only used on the client (for instance, the web browser).

g_form accesses:

Note
Note: The methods getControl(), getElement(), and getFormElement() are deprecated for mobile devices. For more information on using GlideForm for mobile, see Mobile Client GlideForm (g form) Scripting.

Where To Use

These methods are used to make custom changes to the form view of records. All validation of examples was done using Client Scripts.

Some of these methods can also be used in other client scripts (such as Catalog Client Scripts or Wizard Client Scripts), but must first be tested to determine whether they will work as expected.

Enhancements

Fuji

  • New methods are available for getting and setting field labels, and for adding and removing field label icons.

Display Settings

Method Summary
Return Value Details
void addDecoration(fieldName, icon, title)
Adds an icon on a field’s label. This method is available starting with the Fuji release.
void flash(widgetName, color, count)
Flashes the specified color the specified number of times. Used to draw attention to a particular field.
void getLabelOf(fieldname)
Gets the plain text value of the field label. This method is available starting with the Fuji release.
void hideAllFieldMsgs([type])
Hides all field messages.
Optional: Provide type to clear only "info" or "error" messages.
void hideErrorBox(input)
Hides the error message placed by showErrorBox().
Best Practice: Use hideFieldMsg rather than this method whenever possible.
void hideFieldMsg(input, [clearAll])
Hides the message placed by showFieldMsg().
void hideRelatedList(listTableName)
Hides the specified related list on the form.
void hideRelatedLists()
Hides all related lists on the form.
void removeDecoration(fieldName, icon, title)
Removes the icon that matches the exact same name and text. This method is available starting with the Fuji release.
void setDisplay(fieldName, boolean)
Displays the field if true. Hides the field if false. If the field is hidden, the space is reclaimed.
Best Practice: Use UI Policy rather than this method whenever possible.
void setLabelOf(fieldname, label)
Sets the plain text value of the field label. This method is available starting with the Fuji release.
void setVisible(fieldName, boolean)
Displays the field if true. Hides the field if false. If the field is hidden, the space is left blank.
Best Practice: Use UI Policy rather than this method whenever possible.
void showErrorBox(input, message, [scrollForm])
Displays an error message under the specified form field (either a control object or the name of the field). If the control or field is currently scrolled off the screen, it will be scrolled to.
Optional: Set scrollForm to false to prevent scrolling to the error message offscreen.
void 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.
Optional: Set scrollForm to false to prevent scrolling to the field message offscreen.
void showRelatedList(listTableName)
Displays the specified related list on the form.
void showRelatedLists()
Displays all related lists on the form.

Field Information

Method Summary
Return Value Details
Boolean getBooleanValue(fieldName)
Returns false if the field's value is false or undefined, otherwise true is returned.
Useful with checkbox fields. Returns true when the checkbox is checked.
HTMLElement getControl(fieldName)
Returns the HTML element for the specified field. Compound fields may contain several HTML elements.
Generally not necessary as there are built-in methods that use the fields on the form.
HTMLElement getElement(id)
Returns the HTML element for the field specified via the ID. Compound fields may contain several HTML elements.
Generally not necessary as there are built-in methods that use the fields on the form.
int getIntValue(fieldName)
Returns the value of the specified field as an integer. An empty value returns 0.
HTMLElement getOption(fieldName, choiceValue)
Returns the <option> element for a select box named fieldName and where choiceValue matches the option value.
Returns null if the field is not found or the option is not found.
string getReference(fieldName, callback)
Returns the GlideRecord for a specified field.
getReference() accepts a second parameter, a callback function.
Warning: This requires a call to the server so using this function will require additional time and may introduce latency to your page.
string getDecimalValue(fieldName)
Returns the decimal value of the specified field.
string getValue(fieldName)
Returns the value of the specified field.
boolean isMandatory(fieldName)
Returns true if the field is required. Returns false if the field is optional.

Change Field

Method Summary
Return Value Details
void clearValue(fieldName)
Removes any value(s) from the specified field.
void setDisabled(fieldName, boolean)
Grays out field and makes it unavailable.
void setMandatory(fieldName, boolean)
Makes the field required if true. Makes the field optional if false.
Best Practice: Use UI Policy rather than this method whenever possible.
void setReadOnly(fieldName, boolean)
Makes the field read-only if true. Makes the field editable if false.
Note: Both setReadOnly and setReadonly are functional.
Best Practice: Use UI Policy rather than this method whenever possible.
void setValue(fieldName, value, displayValue)
Sets the value and the display value of a field. Will display value if there is no displayValue. To improve performance by preventing a round trip, include a display value in addition to the value.

Note: setValue can cause a stack overflow when used in an OnChange client script. This is because every time the value is set, it will register as a change, which may re-trigger the OnChange client script. To prevent this, perform a check that will validate that the new value will be different from the old value. For example, before performing setValue(fieldName, newValue.toUpperCase());, validate that the short description is not already uppercase. This will prevent the Client Script from applying the toUpperCase() more than once.

Change Choice List

Method Summary
Return Value Details
void addOption(fieldName, choiceValue, choiceLabel, [choiceIndex])
Adds a choice to a choice list field. If the index is not specified, the choice is added to the end of the list.
Optional: Use the index field to specify a particular place in the list.
void clearOptions(fieldName)
Removes all options from a choice list.
void removeOption(fieldName, choiceValue)
Removes a specific option from a choice list.

Form Information

Method Summary
Return Value Details
string getActionName()
Returns the most recent action name or, for a client script, the sys_id of the UI Action clicked. Note: not available to Wizard Client Scripts.
HTMLElement getFormElement()
Returns the HTML element for the form.
string getSectionNames()
Returns all section names, whether visible or not, in an array. This method is available starting with the Fuji release.
string getSections()
Returns the elements for the form's sections in an array.
string getTableName()
Returns the name of the table this record belongs to.
string getUniqueValue()
Returns the sys_id of the record displayed in the form.
boolean isNewRecord()
Returns true if the record has never been saved. Returns false if the record has been saved.
boolean isSectionVisible(sectionName)
Returns true if the section is visible. Returns false if the section is not visible or does not exist. This method is available starting with the Fuji release.

Form Action

Method Summary
Return Value Details
void addErrorMessage(message)
Displays an error message at the top of the form.
void addInfoMessage(message)
Displays an informational message at the top of the form.
void clearMessages()
Removes messages that were previously added with addErrorMessage() and addInfoMessage().
void enableAttachments()
Allows new file attachments to be added. Shows the paperclip icon. See also: disableAttachments().
void disableAttachments()
Prevents new file attachments from being added. Hides the paperclip icon. See also: enableAttachments().
void save()
Saves the record without navigating away from the record (update and stay).
boolean setSectionDisplay(sectionName, display)
Shows or hides a section. Works in both tab and flat modes. This method is available starting with the Fuji release.
void submit()
Saves the record. User will be taken away from the form, returning them to where they were previously.
[top of page]

Display Settings Methods

addDecoration

void addDecoration(fieldName, icon, title)

Adds an icon on a field’s label. Adding the same item twice is prevented; however, you can add the same icon with a different title. This method is available starting with the Fuji release.
Parameters:
fieldname - The field name.
icon - The font icon to show next to the field.
title - The text title for the icon.
Returns:
void
Example:
<source lang="javascript"> g_form.addDecoration(‘caller_id’, ‘icon-star’, ‘preferred member’); </source>
addDecoration_method.png


Note
Note: This method is not supported by Service Catalog.

flash

void flash(widgetName, color, count)

Flashes the specified color the specified number of times in the field. Used to draw attention to a particular field.
Parameters:
widgetName - specifies the field with <table name>.<fieldname>.
color - RGB color or acceptable CSS color like "blue" or "tomato."
count - integer that determines 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
Returns:
void
Example:
<source lang="javascript">g_form.flash("incident.number", "#FFFACD", 0);

</source>

Note
Note: This method is not supported by Service Catalog.

getLabelOf

String getLabelOf(fieldname)

Gets the plain text value of the field label. This method is available starting with the Fuji release.
Parameters:
fieldname - The field name.
Returns:
The label text.
Example:
<source lang="javascript"> if (g_user.hasRole('itil')) { var oldLabel = g_form.getLabelOf('comments'); g_form.setLabelOf('comments', oldLabel + ' (Customer visible)'); } </source>

hideAllFieldMsgs

void hideAllFieldMsgs([type])

Hides all field messages.
Optional: Provide type to hide only "info" or "error" messages.
Parameters:
type (optional) - info or error.
Returns:
void

hideErrorBox

void hideErrorBox(input)

Hides the error message placed by showErrorBox().
Best Practice: Use hideFieldMsg rather than this method whenever possible.
Parameters:
input - specifies the name of the field or control.
Returns:
void

hideFieldMsg

void hideFieldMsg(input, [clearAll])

Hides the message placed by showFieldMsg().
Parameters:
input - specifies the name of the field.
clearAll (optional) - boolean parameter indicating whether to clear all messages. If true, all messages for the field will be cleared; if false or empty, only the last message will be removed.
Returns:
void
Example:
<source lang="javascript">

g_form.hideFieldMsg('impact', true); </source>



hideRelatedList

void hideRelatedList(listTableName)

Hides the specified related list on the form.
Parameters:
listTableName - specifies the name of the related list. Use the list sys_id to hide a list through a relationship.
Returns:
void



hideRelatedLists

void hideRelatedLists()

Hides all related lists on the form.
Returns:
void

removeDecoration

void removeDecoration(fieldName, icon, title)

Removes the icon that matches the exact same name and text. This method is available starting with the Fuji release.
Parameters:
fieldName - The field name..
fieldName - The icon to remove.
fieldName - The text title for the icon.
Returns:
void
Example:
<source lang="javascript">

function onChange(control, oldValue, newValue, isLoading) { // if the caller_id field is not present, then we can't add an icon anywhere if (!g_form.hasField('caller_id')) return;

if (!newValue) return;

g_form.getReference('caller_id', function(ref) { g_form.removeDecoration('caller_id', 'icon-star', 'VIP');

if (ref.getValue('vip') == 'true') g_form.addDecoration('caller_id', 'icon-star', 'VIP'); }); } </source>

Note
Note: This method is not supported by Service Catalog.

setDisplay

void setDisplay(fieldName, boolean)

Displays the field if true. Hides the field if false. This method cannot hide mandatory fields with no value.
If the field is hidden, the space is used to display other items.
Best Practice: Use UI Policy rather than this method whenever possible.
Parameters:
fieldName - specifies the field to be displayed or hidden.
boolean - true to display the field, false to hide the field.
Returns:
void
Example:
<source lang="javascript">

function onChange(control, oldValue, newValue, isLoading, isTemplate) {

  //If the page isn't loading
  if (!isLoading) {
     //If the new value isn't blank
     if (newValue != ) {
        g_form.setDisplay('priority', false);   
     }
     else 
        g_form.setDisplay('priority', true);
     }
  }

</source>

"Priority" Field Displayed
SetDisplayExampleFieldDisplayed.PNG


"Priority" Field Hidden
SetDisplayExampleFieldHidden.PNG



setLabelOf

void setLabelOf(fieldname, label)

Sets the plain text value of the field label. This method is available starting with the Fuji release.
Parameters:
fieldName - The field name.
label - The field label text.
Returns:
void
Example:
This example changes the comments label. <source lang="javascript"> if (g_user.hasRole('itil')) { var oldLabel = g_form.getLabelOf('comments'); g_form.setLabelOf('comments', oldLabel + ' (Customer visible)'); } </source>


Note
Note: This method is not supported by Service Catalog.

setVisible

void setVisible(fieldName, boolean)

Displays the field if true. Hides the field if false.
If the field is hidden, the space is left blank. This method cannot hide mandatory fields with no value.
Best Practice: Use UI Policy rather than this method whenever possible.
Parameters:
fieldName - specifies the field to be displayed or hidden.
boolean - true to display the field, false to hide the field.
Returns:
void
Example:
<source lang="javascript">

function onChange(control, oldValue, newValue, isLoading, isTemplate) {

  //If the page isn't loading
  if (!isLoading) {
     //If the new value isn't blank
     if(newValue != ) {
        g_form.setVisible('priority', false); 
     }
     else
        g_form.setVisible('priority', true); 
     }
  }

</source>

"Priority" Field Displayed
SetVisibleExampleFieldDisplayed.PNG


"Priority" Field Hidden
SetVisibleExampleFieldHidden.PNG




showErrorBox

void showErrorBox(input, message, [scrollForm])

Displays an error message under the specified form field (either a control object or the name of the field). 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).
The showFieldMsg() method is a similar method that requires a "type" parameter.
Optional: Set scrollForm to false to prevent scrolling to the error message offscreen.
Parameters:
input - specifies the name of the field or control.
message - the message to be displayed.
scrollForm (optional) - true to scroll to message if offscreen, false to prevent this scrolling.
Returns:
void
Note: The scroll form functionality for showErrorBox does not work in CMS with Catalog Items.

showFieldMsg

void 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).
The showErrorBox() method is a shorthand method that does not require the "type" parameter.
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.
Returns:
void
Example - Informational Message:
<source lang="javascript">

g_form.showFieldMsg('impact','Low impact response time can be one week','info'); </source>

Image:showFieldMsgInfo.PNG

Example - Error Message:
<source lang="javascript">

g_form.showFieldMsg('impact','Low impact not allowed with High priority','error'); </source>

Image:showFieldMsgError.PNG


showRelatedList

void showRelatedList(listTableName)

Displays the specified related list on the form.
Parameters:
listTableName - specifies the name of the related list.
Returns:
void

showRelatedLists

void showRelatedLists()

Displays all related lists on the form.
Returns:
void


[top of page]

Field Information Methods

getBooleanValue

Boolean getBooleanValue(fieldName)

Returns false if the field value is false or undefined, otherwise returns true.
Parameters:
fieldName - specifies the name of the field.
Returns:
Boolean - the boolean value of the field.

getControl

HTMLElement getControl(fieldName)

Returns the HTML element for the specified field. Compound fields may contain several HTML elements.
Generally not necessary as there are built-in methods that use the fields on the form.
Parameters:
fieldName - specifies the name of the field.
Returns:
HTMLElement - the specified HTML element(s).
Note: If the field is of type reference and the control is a choice list, getControl() may not return control as expected. In this case, use sys_select.<table name>.<field name>.

getElement

HTMLElement getElement(id)

Returns the HTML element for the field specified by the ID. Compound fields may contain several HTML elements.
Generally not necessary as there are built-in methods that use the fields on the form.
Parameters:
id - specifies the field ID.
Returns:
HTMLElement - the specified HTML element(s).

getIntValue

int getIntValue(fieldName)

Returns the value of the specified field as an integer. An empty value returns 0.
Closely related to getValue().
Parameters:
fieldName - specifies the field.
Returns:
integer - value of the specified field as an integer.

getOption

HTMLElement getOption(fieldName, choiceValue)

Returns the <option> element for a select box named fieldName and where choiceValue matches the option value.
Returns null if the field is not found or the option is not found.
Parameters:
fieldName - specifies the name of the field.
choiceValue - specifies the value of the option to return.
Returns:
HTMLElement - the specified HTML element.

getReference

GlideRecord getReference(fieldName, callback)

Returns the GlideRecord for the record specified in a reference field. If the referenced record cannot be found, then it returns an initialized GlideRecord object where currentRow = -1 and rows.length = 0.
getReference() accepts a second parameter, a callback function.
Callback function support for ServiceCatalogForm.getReference is available.
Warning: This requires a call to the server so using this function will require additional time and may introduce latency to your page. Use with caution. See Avoid Server Lookups.
Parameters:
fieldName - specifies the reference field.
Returns:
GlideRecord - the GlideRecord object for the record in specified in the reference field. See GlideRecord for more information.
  • If a callback function is present, this routine runs asynchronously, and browser (and script) processing will continue normally until the server returns the reference value, at which time the callback function will be invoked.
  • If a callback function is not present, this routine runs synchronously and processing will halt (causing the browser to appear to hang) while waiting on a server response. It is strongly recommended that a callback function be used on any supported versions.


Example: without a callback (don't do this)
<source lang="javascript">

function onChange(control, oldValue, newValue, isLoading) {

  var caller = g_form.getReference('caller_id');
  if (caller.vip == 'true')
     alert('Caller is a VIP!');

}</source>

Example: with a callback (recommended)
<source lang="javascript">

function onChange(control, oldValue, newValue, isLoading) {

  var caller = g_form.getReference('caller_id', doAlert); // doAlert is our callback function

} function doAlert(caller) { //reference is passed into callback as first arguments

 if (caller.vip == 'true')
   alert('Caller is a VIP!');

} </source>


getValue

string getValue(fieldName)

Returns the value of the specified field.
Parameters:
fieldName - specifies the field.
Returns:
string - the value of the specified field.
Example:
<source lang="javascript">

function onChange(control, oldValue, newValue, isLoading) {

  alert(g_form.getValue('short_description'));

} </source>

Example:
<source lang="JavaScript">
 function onChange(control, oldValue, newValue, isLoading)
 if (isLoading) 
     return;
 if (!g_form.isNewRecord())
     return;
 var lookup = new GlideRecord('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', "");
   }
 }

}


function onLoad() {

  if(g_form.isNewRecord()){
     alert('New Record!');
  }

} </source>

getDecimalValue

string getDecimalValue(fieldName)

Returns the decimal value of the specified field.
Parameters:
fieldName - specifies the field.
Returns:
string - the value of the specified field.
Example:
<source lang="javascript">

function onChange(control, oldValue, newValue, isLoading) {

  alert(g_form.getValue('percent_complete'));

} </source>


isMandatory

boolean isMandatory(fieldName)

Returns true if the field is mandatory.
Parameters:
fieldName - specifies the field.
Returns:
boolean - true if the field is required, false if it is optional.


[top of page]

Change Field Methods

clearValue

void clearValue(fieldName)

Removes any value(s) from the specified field.
Parameters:
fieldName - specifies the field.
Returns:
void



setDisabled

void setDisabled(fieldName, boolean)

Grays out field and makes it unavailable.
Parameters:
fieldName - specifies the field.
boolean - true if disabled, false if enabled.
Returns:
void

setMandatory

void setMandatory(fieldName, boolean)

Makes the field required if true.
Best Practice: Use UI Policy rather than this method whenever possible.
Parameters:
fieldName - specifies the field.
boolean - true if mandatory, false if optional.
Returns:
void

setReadOnly

void setReadOnly(fieldName, boolean)

Makes the field read-only if true, editable if false. To make a mandatory field read-only, you must first remove the mandatory requirement for that field by using the setMandatory method.
Note: Both setReadOnly and setReadonly are functional.
Best Practice: Use UI Policy rather than this method whenever possible.
Parameters:
fieldName - specifies the field.
boolean - true if read-only, false if editable.
Returns:
void

setValue

void setValue(fieldName, value, [displayValue])

Sets the value and the display value (if provided) of a field. When defining a value in a choice list, be sure to use number value rather than the label.

To improve performance by preventing a round trip, include a display value in addition to the value.

Note: setValue can cause a stack overflow when used in an OnChange client script. This is because every time the value is set, it will register as a change, which may re-trigger the OnChange client script. To prevent this, perform a check that will validate that the new value will be different from the old value. For example, before performing setValue(fieldName, newValue.toUpperCase());, validate that the short description is not already uppercase. This will prevent the Client Script from applying the toUpperCase() more than once.

Parameters:
fieldName - specifies the field.
value - value in database.
displayValue (optional) - value that will be displayed.
Returns:
void
Example: Setting Display to Value
<source lang="javascript">

g_form.setValue('short_description', 'replace this with appropriate text'); </source>

Example: Setting Display to Display Values
<source lang="javascript">

var valueArray = new Array("46d44a23a9fe19810012d100cca80666", "46c6f9efa9fe198101ddf5eed9adf6e7"); var labelArray = new Array("Beth Anglin", "Bud Richman"); g_form.setValue("watch_list", valueArray, labelArray); </source>

Example: Setting Display to Glide List
<source lang="JavaScript">

//Set Assignment Group to CI's support group if assignment group is empty function onChange(control, oldValue, newValue, isLoading) {

  if (!isLoading) {
     if (newValue) {
        if (newValue != oldValue) {
           if (g_form.getValue('assignment_group' != ) {
              var ciSupportGroup = g_form.getReference('cmdb_ci').support_group;
              if (ciSupportGroup != ) 
                 g_form.setValue('assignment_group', ciSupportGroup);
           }
        }
     }
  }

} </source>



[top of page]

Change Choice List Methods

addOption

void addOption(fieldName, choiceValue, choiceLabel, [choiceIndex]))

Adds a choice to a choice list field. If the index is not specified, the choice parameter is added to the end of the list.
Optional: Use the index field to specify a particular place in the list.
Parameters:
fieldName - specifies the field.
choiceValue - the value stored in the database.
choiceLabel - the value displayed.
choiceIndex (optional) - order of choice in the list.
Returns:
void
Example - Add an Option to the End of a Choice List:
<source lang="javascript">g_form.addOption('priority', '6', '6 - Really Low');</source>
Example - Add an Option at a Specific Point on a Choice List:
<source lang="javascript">g_form.addOption('priority', '2.5', '2.5 - Moderately High', 3);</source>
Note that an insert will happen at the location you specify on a zero based array. Existing options will all shift up one level. For example, given:
[A, B, C, D]
Insert E at 0
[E, A, B, C, D]
Insert E at 2
[A, B, E, C, D]



clearOptions

void clearOptions(fieldName)

Removes all options from a choice list.
Parameters:
fieldName - specifies the field.
Returns:
void



removeOption

void removeOption(fieldName, choiceValue)

Removes a specific option from a choice list.
Note: (Versions prior to Eureka) When items are removed from a choice list by a Client Script, Google Chrome and Apple Safari will still display those items. When one of these web browsers is used, the "removed" items will be displayed as read only in the choice list and they cannot be chosen.
Parameters:
fieldName - specifies the field.
choiceValue - specifies the value stored in the database as a choice.
Returns:
void
Example: Remove the '1' Option from the Priority Field
<source lang="javascript">

g_form.removeOption('priority', '1'); </source>

Example: Remove the 'Closed' State Option if the User is not an Admin
<source lang="javascript">

function onLoad() {

  var isAdmin = g_user.hasRole('admin');
  var incidentState = g_form.getValue('incident_state');
  if (!isAdmin && (incidentState != 7)){
     g_form.removeOption('incident_state', '7');
  }

} </source>




[top of page]

Form Information Methods

getActionName

string getActionName()

Returns the most recent action name or, for a client script, the sys_id of the UI Action clicked. Note: not available in Wizard Client Scripts.
Returns:
string - current action name.
Example:
<source lang="javascript">

function onSubmit() {

  var action = g_form.getActionName();
  alert('You pressed ' + action);

} </source>


getFormElement

HTMLFormElement getFormElement()

Returns the HTML element for the form.
Returns:
HTMLFormElement - returns the HTML element for the form.

getSectionNames

array getSectionNames()

Returns all section names, whether visible or not, in an array.
Returns:
array - the segment names.

getSections

array getSections()

Returns the elements for the form's sections in an array.
Returns:
array - the HTML Elements for the form.
Example:
<source lang="javascript">function onChange(control, oldValue, newValue, isLoading) {
  //this example was run on a form divided into sections (Change form)
  // and hid a section when the "state" field was changed
  var sections = g_form.getSections();
  if (newValue == '2') {
     g_form.setSectionDisplay(sections[1], false);
  } else {
     g_form.setSectionDisplay(sections[1], true);
  }

} </source>



getTableName

string getTableName()

Returns the name of the table this record belongs to. On the server side, the table for the current record can be retrieved with current.sys_class_name or current.getTableName().
Returns:
string - table name.
Example:
<source lang="javascript">

function onLoad() {

   if (g_form.isNewRecord() {
       var tableName = g_form.getTableName(); //Get the table name
   }

} </source>



getUniqueValue

string getUniqueValue()

Returns the sys_id of the record displayed in the form.
Returns:
string - sys_id.
Example:
<source lang="javascript">

function onLoad() {

  var incSysid = g_form.getUniqueValue();
  alert(incSysid);

} </source>


isNewRecord

boolean isNewRecord()

Returns true if the record has never been saved.
Returns:
boolean - true if record has not been saved, false if it has been saved.
Example:
<source lang="javascript">function onLoad() {
  if(g_form.isNewRecord()){
     alert('New Record!');
  }

} </source>

Example:
<source lang="JavaScript">

function submitConfirm() {

   if (confirm('Are you sure you want to submit a priority one incident?')) {
       g_form.setValue('priority', '1');
       if (g_form.isNewRecord()) {
           g_form.save();
       } else {
           g_form.submit();
       }
   }

} </source>


isSectionVisible

boolean isSectionVisible(sectionName)

Returns true if the section is visible. Returns false if the section is not visible.
Returns:
boolean - true if the section is visible. Returns false if the section is not visible.


[top of page]

Form Action Methods

addErrorMessage

void addErrorMessage(message)

Displays an error message at the top of the form.
Parameters:
message - the error message to be displayed.
Returns:
void
Example
<source lang="javascript">

g_form.addErrorMessage('This is an error'); </source>

Image:AddErrorMessage.PNG


addInfoMessage

void addInfoMessage(message)

Displays an informational message at the top of the form.
Parameters:
message - the informational message to be displayed.
Returns:
void
Example
<source lang="javascript">

g_form.addInfoMessage('The top five fields in this form are mandatory'); </source>

Image:AddInfoMessage.PNG


clearMessages

void clearMessages()

Removes all informational and error messages that were added with both g_form.addInfoMessage and g_form.addErrorMessage.
Returns:
void
Example
<source lang="javascript">

g_form.clearMessages(); </source>


enableAttachments

void enableAttachments()

Allows new file attachments to be added. Shows the paperclip icon. See also: disableAttachments().
Returns:
void

disableAttachments

void disableAttachments()

Prevents new file attachments from being added. Hides the paperclip icon.
Returns:
void

save

void save()

Saves the record without navigating away from the record (update and stay).
Returns:
void

setSectionDisplay

boolean setSectionDisplay(sectionName, display)

Parameters:
sectionName - name of the section to be shown or hidden. The section name is lower case with an underscore replacing the first space in the name, and with the remaining spaces being removed, for example "Section Four is Here" becomes "section_fourishere". Other non-alphanumeric characters, such as ampersand (&), are removed. Section names can be found by using the getSectionNames method.
display - set true to show, false to hide.
Returns:
Boolean - true if successful.

submit

void submit()

Saves the record. User will be taken away from the form, returning them to where they were previously.
Returns:
void


[top of page]


Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Change Form Color on State Change

Type: Client Script

Table:

Description: Changes color of a form field of the form on state change. The script can easily be changed to adjust any property of any object on the page accessible via the HTML DOM.

Parameters:

Script: <source lang="javascript"> function onChange(control, oldValue, newValue, isLoading) {

 var elementID = gel("incident.priority");
 switch (newValue) {
   case "1":
     elementID.style.backgroundColor = "red";
     break;
   case "2":
     elementID.style.backgroundColor = "tomato";
     break;
   case "3":
     elementID.style.backgroundColor = "orange";
     break;
   case "4":
     elementID.style.backgroundColor = "yellow";
     break;
   case "5":
     elementID.style.backgroundColor = "green";
     break;
   default:
     elementID.style.backgroundColor = "white";
     break;
 }

} </source>

Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Collapse Section on Forms

Type: Client Script

Table:

Description: This example is set to enable collapse/expanding of the Activity section on the task form.

The default function called when you click the box icon to collapse the activity section is:

ActivityFilter.toggleActivity(false);

However, this function always toggles the section. If it is already collapsed, toggleActivity will expand it. Here's an onLoad client script that will only collapse the entire activity section on the incident form.

Parameters:

Script: <source lang="javascript"> ActivityFilter.hideActivity = function(table, key) { var fDiv = gel('toggle_activity.' + key); setPreference(table + ".activity.log.display", "none", null); fDiv.style.display = 'none'; }

function onLoad() { try { ActivityFilter.hideActivity(g_form.getTableName(),g_form.getUniqueValue()); } catch (err) { //do nothing } } </source>

Note
Note: This article applies to Fuji. For more current information, see Display Field Messages at http://docs.servicenow.com

The ServiceNow Wiki is no longer being updated. Please refer to http://docs.servicenow.com for the latest product documentation.

Overview

Rather than use JavaScript alert(), for a cleaner look, you can display an error on the form itself. The methods showFieldMsg() and hideFieldMsg() can be used to display a message just below the field itself.

showFieldMsg and hideFieldMsg are methods that can be used with the g_form object (see GlideForm (g_form)).

These methods are used to make changes to the form view of records (Incident, Problem, and Change forms). These methods may also be available in other client scripts, but must be tested to determine whether they will work as expected.

When a field message is displayed on a form on load, the form will scroll to ensure that the field message is visible, ensuring that users will not miss a field message because it was off the screen.

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

Method

showFieldMsg(input, message, type, [scrollform]);
input - name of the field or control
message - message you would like to display
type - either 'info' or 'error', defaults to info if not supplied
scroll form - (optional) Set scrollForm to false to prevent scrolling to the field message offscreen.


hideFieldMsg(input);
input - name of the field or control *clearAll - (optional) boolean parameter indicating whether to clear all messages. If true, all messages for the field will be cleared; if false or empty, only the last message will be removed.

Example

Error Message

<source lang="javascript"> g_form.showFieldMsg('impact','Low impact not allowed with High priority','error'); </source>
Image:showFieldMsgError.PNG

Informational Message

<source lang="javascript"> g_form.showFieldMsg('impact','Low impact response time can be one week','info'); //or this defaults to info type //g_form.showFieldMsg('impact','Low impact response time can be one week'); </source>
Image:showFieldMsgInfo.PNG

Removing a Message

<source lang="javascript"> //this will clear the last message printed to the field g_form.hideFieldMsg('impact'); </source>

Legacy Support

The showErrorBox() and hideErrorBox() are still available but simply call the new methods with type of error. It is recommended that you use the new methods.

Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Enable Collapsing Related Lists

Type: onLoad Client Script

Table: Incident

Description: Now that you can collapse/expand related list sections on the form, you might want to do the same using client scripts. The default function called when you click the +/- icon is:

toggleSectionDisplay('partialPage:task_ci_task_list');

This function manages the collapse/expand effect. As it's name implies it is a toggle effect so there is no way force a section to be collapsed or expanded since it will just toggle whatever the current state is. It also saves the setting as a user preference so the list will be displayed the same way the next time the form is loaded. You will probably want to change the effect of a list without updating or restoring the user's preferences. In this case there are other functions that can be used to simply change the display style on the list element.

Below is an onLoad client script that will collapse all of the related list sections on a form.

Parameters:

Script: <source lang="javascript">function onLoad() {

//Client Script: Collapse All Lists on Load //Type: onLoad //Table: Incident

 //get array of span elements on the page
 var spans = document.getElementsByTagName('span');
 //walk the array
 for (var i = 0; i < spans.length; i++) {
   //check for spans matching section.partialPage naming, these are related lists 
   if (spans[i].id.substr(0, 20) == "section.partialPage:") {
     //get the element id for the section
     var id = spans[i].id.substring(8);
     //collapse the list    
     forceHide(id); 
     //to expand use -- forceReveal(id);
   }
 }

} </source>

Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Modify Fields Based on State

Type: onLoad Client Script

Table:

Description:

Parameters:

Script:

<source lang="javascript"> // 1 - Awaiting Assessment // 2 - Analysis Internal // 3 - Analysis External // 4 - Root Cause FOund // 5 - Known Error // 6 - Resolved // 7 - Closed // 8 - Not Used

// This script manages the presentation of the available Incident States according to a state transition matrix. // As its an onload I have coded the valid transitions as part of the script instead of designing a table to look them up. // At the database level the values are numeric so thats the way they need to be processed. Also the logic needs to be // reversed because its better to remove options than clear them all and re-add them // the simplest way to do this is a bunch of 'if (state = blah) then remove options'. // however I have coded this to make it easier to maintain the state transitions. // To use elsewhere need to edit the vNoStates variable below and the transitions in the function below

function onLoad() {

var vNoStates = 7;

var vState = g_form.getValue('problem_state');

var vTransitions = []; // create the array; vTransitions = getTransitions(vState);


var vTransLen = vTransitions.length;

var i = 0; for (i=1; i<=vNoStates; i++) {

var isItThere = vTransitions.indexOf(i);

if (isItThere == -1) { g_form.removeOption('problem_state', i); } }

}

function getTransitions(vStatus) { var vState = []; // declare states and values here var AwaitingAssessment = 1; var AnalysisInternal = 2; var AnalysisExternal = 3; var RootCauseFound = 4; var KnownError = 5; var Resolved = 6; var Closed = 7;


vState[AwaitingAssessment] = [AwaitingAssessment, AnalysisInternal, AnalysisExternal]; vState[AnalysisInternal] = [AnalysisInternal, AnalysisExternal, RootCauseFound, KnownError]; vState[AnalysisExternal] = [AnalysisInternal, AnalysisExternal, RootCauseFound, KnownError]; vState[RootCauseFound] = [RootCauseFound, Resolved]; vState[KnownError] = [KnownError, Resolved]; vState[Resolved] = [Resolved, Closed, AnalysisInternal, AnalysisExternal]; vState[Closed] = [Closed];

return(vState[vStatus]); </source>

Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Remove Attachment Field from Form

Type: Client Script

Table: incident

Description: Removes the attachment field from a record. This script must be included on each form. This example is for incident forms. For a global solution, see: Granting Roles Access to Attachments

Parameters:

Script: <source lang="javascript">function onLoad() { var strVal = "javascript:saveAttachment('incident', );"; var arrLink = document.getElementsByTagName('a'); var intLen = arrLink.length;

for (var intCnt = 0; intCnt < intLen; intCnt++) { strAttrib = arrLink[intCnt].getAttribute && arrLink[intCnt].getAttribute('href');

if (strAttrib == strVal) { arrLink[intCnt].style.display = 'none'; } } }</source>

In case the script does not work, try the alternative approach provided below.

<source lang="javascript"> function onLoad() {

var refs = document.getElementsByTagName("a");
if (refs) {
 for (var i=0; i < refs.length; i++) {
  var ref = refs[i];
  var inner = ref.innerHTML;
  if (inner.indexOf("attachment.gifx") > 0){
     ref.style.display = 'none';
    }
  }
}

}</source>

Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Remove Attachments Link

Type: Client Script

Table:

Description: Below is an onLoad script that will remove the attachments link for end-users. The key here is the "strVal" variable. This is specific to incident - and if development decides to change how the "saveAttachment" function is used, it could break this script. You still need to look for roles or else this will apply to everybody

Parameters:

Script: <source lang="javascript">function onLoad() { var strVal = "javascript:saveAttachment('incident', );"; var arrLink = document.getElementsByTagName('a'); var intLen = arrLink.length;

for (var intCnt = 0; intCnt < intLen; intCnt++) { strAttrib = arrLink[intCnt].getAttribute && arrLink[intCnt].getAttribute('href');

if (strAttrib == strVal) { arrLink[intCnt].style.display = 'none'; } } }</source>

Note
Note: The ServiceNow Wiki is no longer being updated. Please refer to http://docs.servicenow.com for the latest product documentation.


Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}
As-is functionality
Caution: The customization described here was developed for use in specific ServiceNow instances, and is not supported by ServiceNow Customer Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community forum.

Name: Set Default Value for Reference Fields

Type: Business Rule

Table:

Description: Let's say that you want to set the default value for the assignment_group field to "Help Desk". You might be tempted to just set the default value to exactly what you want to be: "Help Desk". If you do so, you will find that it just does not work. It does not work because assignment_group is a reference field which means that it actually "points" to another file. assignment_group is a reference to a record in the "sys_user_group" table and references to other tables are done via an internal field called "sys_id". Here is a helper javascript function you can call to get the ID value that is associated with a record given that records display value. This helper function should be created in a global business rule.

Parameters:

Script: <source lang="javascript"> // Return the sys_id value for a given table and its display value // function GetIDValue(table, displayValue) {

var rec = new GlideRecord(table);
var dn = gs.getDisplayColumn(table);
if (rec.get(dn, displayValue))
   return rec.sys_id;
else
   return null;

} </source> Then the default value for the assignment_group field will be:

javascript:GetIDValue("sys_user_group", "Help Desk");
Role required
Functionality described here requires {{ #if: Admin | the Admin role. | specific roles. }}

Overview

It is possible, using a client script, to warn a user if the record they are about to update has been modified by someone else since the time they opened it in their browser. Consider the following scenario:

  1. User A opens an incident in their browser
  2. User B opens the same incident a few seconds later
  3. User A updates/saves the incident
  4. User B updates/saves the incident

By default, User B's update will overwrite User A's changes. User A's journal comments (Additional comments and Work notes) will be preserved, but any other changes would only be available in the Incident history.

Note
Note: The script should not be used on instances that have the Fuji release of ServiceNow installed. See KB0551171 for more information.



With the creation of an onSubmit() client script, it is possible to warn the second user if the record has changed in the database since they opened it, and provide an opportunity to abort the second update. The below example is for Incident records, but it is applicable to any record. This can be considered an alternative to record locking. The text of the script is below for easy cutting and pasting:


<source lang="javascript">// For support of warning when two people are editing the same record.

function onSubmit() {
  var updatedOn = gel('onLoad_sys_updated_on');
  if (!updatedOn)
     return;
     
  updatedOn = updatedOn.value;
  if (!updatedOn)
     return;
  var sysid_gel = gel('sys_uniqueValue');
  var sysid = sysid_gel.value;
  var gr = new GlideRecord('incident');
  gr.addQuery('sys_id',sysid);
  gr.query();
  if (gr.next()) {
     var dbUpdatedOn = gr.sys_updated_on + ;
     var dbUpdatedBy = gr.sys_updated_by + ;
  } else
     return;
  if (updatedOn != dbUpdatedOn) {
     return confirm("Record has been updated by " + dbUpdatedBy + " since you opened it - "
     + "overwrite those changes with yours? Note that Additional comments and Work notes are "
     + "additive and will not be overwritten.");
  }
}

</source>