Each addQuery() call adds a new AND'ed "where" clause (not seen by the user). query() executes the select statement and returns zero or more records.
addOrCondition() - OR logic
varmyObj=newGlideRecord('change_request');varq1=myObj.addQuery('category','=','Hardware');q1.addOrCondition('priority','!=',1);myObj.query();// Equivalent, chained in one line
myObj.addQuery('category','=','Hardware').addOrCondition('priority','!=',1);
Use addQuery() for the first condition, then call addOrCondition() on the returned QueryCondition to OR in a second: select * from change_request where category = 'Hardware' OR priority != 1.
Passes all query "where" clauses as a single argument, building the SQL select statement (not seen by the user) - the best option when you're in a hurry.
03
Insert, Update, Delete
Update
varincGR=newGlideRecord('incident');incGR.addQuery('problem_id','=',current.sys_id);incGR.query();while(incGR.next()){incGR.work_notes="Related Problem "+current.number+" closed with the following Close Notes:\n\n"+current.close_notes;incGR.update();}
Use the update() method to save changes to the records in the GlideRecord. If the record does not exist, it is inserted.
04
GlideAggregate
Confirm records returned
varmyObj=newGlideRecord('incident');myObj.addQuery('caller_id',current.caller_id);myObj.query();varretRows=myObj.getRowCount();gs.info("Returned number of rows = "+retRows);varcount=newGlideAggregate('incident');count.addQuery('caller_id',current.caller_id);count.addAggregate('COUNT');count.query();varincidents=0;if(count.next()){incidents=count.getAggregate('COUNT');}gs.info("Returned number of rows = "+incidents);
getRowCount() takes less code but has a larger performance impact. GlideAggregate() takes more code but executes faster.
05
GlideQuery
An alternative to GlideRecord
Server-side API for querying data
Written in 100% JavaScript (global Script Include)
Uses GlideRecord behind the scenes
Guided by three principles: Fail Fast -improve the feedback loop, surface errors as soon as possible. Be JavaScript -behaves like normal JavaScript, unlike GlideRecord's mix of Java and JavaScript elements. Be Expressive -do more with less code; fluent, chainable style.
GlideDateTime.subtract() returns a GlideDuration - use getDisplayValue() for a human-readable 1 Day 02:15:00, or getNumericValue() for milliseconds.
Check current time against a schedule
varschedule=newGlideSchedule("090eecae0a0a0b260077e1dfa71da828");varcurrentDateTime=newGlideDateTime();if(schedule.isInSchedule(currentDateTime)){gs.print("The schedule is active.");}else{gs.print("The schedule is not active.");}
Pass the sys_id of a cmn_schedule record to GlideSchedule, then use isInSchedule() to check a GlideDateTime against it
08
Client Scripts - g_form
The three script types
Type
Runs when
onLoad
The form finishes loading - good for setting initial field state
onChange
A specific field's value changes - receives oldValue/newValue
onSubmit
The form is submitted, before save - return false to stop the submit
A fourth type, onCellEdit, fires on inline list edits instead of a form.
Common g_form methods
Method
Purpose
g_form.getValue(field)
Read a field's value
g_form.setValue(field, value)
Set a field's value
g_form.getDisplayValue(field)
Read a reference field's display value
g_form.setMandatory(field, bool)
Toggle mandatory
g_form.setReadOnly(field, bool)
Toggle read-only
g_form.setVisible(field, bool)
Show/hide a field
g_form.addInfoMessage(msg) / addErrorMessage(msg)
Show a message on the form immediately
g_form.getReference(field, callback)
Async-fetch the full record behind a reference field
onChange skeleton
functiononChange(control,oldValue,newValue,isLoading,isTemplate){if(isLoading||newValue===''){return;}if(newValue==='critical'){g_form.setMandatory('assignment_group',true);g_form.addInfoMessage('Critical priority requires an assignment group.');}}
Always guard with isLoading/empty-value checks first - onChange fires while the form loads too, not just on user edits.
09
Business Rules
When to run
Timing
Runs
Use for
before query
Before the DB query executes (sync)
Restrict/filter what records come back - no ACL-style "rows removed" message
display
After the query, before the form renders
Populate g_scratchpad so client scripts can read values with no server round-trip
before
After submit, before the write (sync)
Modifying current before it is written - no update() needed
after
After submit *and* after the write (sync)
Cascading changes to *other* records once this one is saved
async
In the background as a scheduled job
Slow work (notifications, SLA calcs), no previous - prefer over after when possible; order multiple with priority
Order of execution: before query → display → before → after → async. Before/after/query rules run synchronously - each must finish before the next starts - while async runs independently so the user's transaction isn't held up.
10
Script Includes
Three types of Script Includes
Type
Behavior
Store one classless function
One re-usable function; server-side only; a.k.a. "on demand"
Define a new class
Collection of functions; callable from client-side scripts; convention is to suffix the name with Utils (e.g. TravelRequestUtils)
Extend an existing class
Adds functionality to an existing class (typically AbstractAjaxProcessor); callable from client-side scripts
Classless / on-demand Script Include
functionhasRoleExactly(userSysID,roleString){try{varroleGr=newGlideRecord("sys_user_role");if(roleGr.get('name',roleString)){varrole=roleGr.getValue('sys_id');vargr=newGlideRecord("sys_user_has_role");gr.addQuery("user",userSysID);gr.addQuery("role",role);gr.query();if(gr.next()){returntrue;}else{returnfalse;}}}catch(error){gs.error("Error in Script Include hasRoleExactly: "+error);}}
Stores a single function and is server-side only -not callable from the client, even if "Client callable" is checked. The Script Include's name must be identical to the function name.
Anything set in initialize() becomes a global property available to every function in the class - declare shared setup (like the current user's record) once instead of repeating it. Convention is to suffix the class name with Utils.
Steps: create a GlideAjax object for the Script Include of interest → pass parameters (all names begin with sysparm_; the reserved sysparm_name identifies which method to call) → the call is asynchronous, so a callback function processes the returned data. getXML() hands back a raw XML response - pull the value out manually with response.responseXML.documentElement.getAttribute('answer').
Returning JSON from a Script Include
varCallerIncidents=Class.create();CallerIncidents.prototype=Object.extendsObject(AbstractAjaxProcessor,{getCallersIncs:function(){varincArray=[];//Create an empty array
varcallersRecords=newGlideRecord('incident');callersRecords.addQuery('caller_id',this.getParameter('sysparm_callerID'));callersRecords.query();while(callersRecords.next()){//Build the array of objects
varincDetails={};incDetails.number=callersRecords.number.toString();incDetails.priority=callersRecords.priority.getDisplayValue();incDetails.shortDesc=callersRecords.short_description.toString();incArray.push(incDetails);}//Create a string from a JSON object and pass it back to the calling script
returnJSON.stringify(incArray);},type:'CallerIncidents'});
The stringified JSON comes back wrapped in an XML answer attribute, e.g. <xml answer="[{...}]" sysparm_name="callerIncidents" ...></xml>.
Parsing a JSON response client-side
//Create a GlideAjax object and call the Script Include
varincGA=newGlideAjax('CallerIncidents');incGA.addParam('sysparm_name','getCallersIncs');incGA.addParam('sysparm_callerID',g_form.getValue('caller_id'));incGA.getXMLAnswer(CallerIncidentsParse);functionCallerIncidentsParse(response){//Build an array of objects from the JSON object and take action
varmyObj=JSON.parse(response);g_form.addInfoMessage('User has raised the following incidents:');for(vari=0;i<myObj.length;i++){g_form.addInfoMessage(myObj[i].number+': '+myObj[i].shortDesc);}}
getXMLAnswer() auto-extracts the answer attribute for you, so the callback can JSON.parse(response) directly - no manual responseXML.documentElement.getAttribute(...) needed like plain getXML().
11
Navigation & Debugging
URL shortcuts
/incident_list.do?sysparm_query=active=true
/incident.do?sys_id=-1 new record
/sys.scripts.do background scripts
/sys_properties_list.do all properties
/syslog_list.do platform logs
/stats.do instance stats
/cache.do flush the cache
/nav_to.do?uri=incident_list.do
Typing incident.list or incident.form in the filter navigator jumps straight to a list or blank form.
All Menu Navigation
incident.do new form
incident.list list records
incident.config configs for table
stats.do instance stats
cache.do flush the cache
Typing .do, .list, or .config after a table name in the filter navigator jumps straight to the list, form, or table configuration. If you capitalize it (e.g., incident.LIST), it opens in a new tab.