logo

NJP

Script conservation - a GlideRecord shortcut

Import · Oct 21, 2011 · article

I'm pretty lazy. So I don't like writing more lines of script that are essential. Case in point, my very first business rule, written maybe five-and-a-half years ago, did about 4 different things but only had one line. (It was a horrible script - I was a Math major and apparently thought I was writing equations instead of scripts.)Sometimes you need to do a GlideRecord query just to get a single record based on a single value, e.g. a user record with a specific name. One might do that like this:

doit();function doit() { var user = new GlideRecord("sys_user"); user.addQuery("name", "Beth Anglin"); user.query(); if (!user.next())<!--break--> return; gs.print("Found her: " + gr.name);}

Many scripters are familiar w/ the get() method of GlideRecord that lets you get a record by its sys_id, avoiding the need for a query() and a next(). e.g.:

var user = new GlideRecord("sys_user"); user.get("ab4738df93ea83fbab4738df93ea83fb"); gs.print("Found her: " + user.name);

But get() can also be passed TWO parameters, the first being a field name and the second being a value. So the first script above could be shortened to the following:

doit();function doit() { var user = new GlideRecord("sys_user"); if (!user.get("name", "Beth Anglin")) return; gs.print("Found her: " + gr.name);}

View original source

https://www.servicenow.com/community/in-other-news/script-conservation-a-gliderecord-shortcut/ba-p/2282432