Shortcut GlideRecord Queries with get

Tutorial on the GlideRecord get() method to return a single record

#GlideRecord , #GlideRecord get , #get , #Scripting , #Server Side Scripting

Ben Sweetser

9 minute read

We are experimenting with new training content delivery methods. This tutorial blog post is one of those experiments. We are very interested in your feedback. Please let us know what you think about this format and the content in the comments below.

Introduction

Sometimes you know exactly what you want. You do not have the server at a restaurant bring you every chicken item on the menu and then decide which to eat. You just select the dish you want. When you order directly, you use fewer resources.

Directly retrieve a specific record in a single line of code with the GlideRecord get() method. A typical GlideRecord query to get the same record requires steps to:

  • addQuery
  • query
  • next

The topics in this post build on concepts in the GlideRecord concepts in the Server-side Scripting module.

In this post, you create Business Rules that use the get() method to get a record or to check for the existance of at least one matching record.

  • Guided: Create a Business Rule to get the contact for printer-related incidents and write contact details to a comment.
  • Challenge: Create a Business Rule for a NeedIt record that gets contact information for patent questions.
  • Guided: Use get() to determine if a user is a caller on any other incident.

NOTE: This exercise uses demo data that may vary in your instance.

Create a Business Rule to Get a Contact for Printer Incidents

The scenario: Your company leases printers, but is expected to support the printers. If needed, IT can contact the leasing company for additional support. The contact details should be written to Description field on an incident for the person assigned the incident to reference. The person who maintains the business relationship with the printer company is not a scripter and needs to be able to change the contact details outside of a script.

In this section, you create a printer contact User record. Then you create a Business Rule that checks for the word printer in the Short description for an Incident. If the word printer is found, the Business Rule gets the printer contact details to update the Description.

  1. Log in to your ServiceNow instance as a System Administrator.
  2. Create a User record for the printer contact and copy the Sys ID.
    1. Use the Application Navigator to open User Administration > Users.
    2. Click the New button.
    3. Configure the User record.
      1. User ID: printer.contact
      2. First name: Printer
      3. Last name: Contact
      4. Email: pc@zeerocks.com
      5. Business phone: (212) 987-6789
    4. Click the Additional actions ( Additional actions button ) button and select the Save menu item.
    5. Click the Additional actions button and select the Copy sys_id menu item.
    6. Paste the Sys ID some place easy to copy it from later.
  3. Create a Business Rule.

    1. Use the Application Navigator to open Incident > Open.
    2. Click any column header menu and select the Configure > Business Rules menu item.
    3. Click the New button.
    4. Configure the Business Rule.
      1. Name: Add Printer Contact Comment
      2. Advanced: selected (checked)
    5. Configure the When to run section.
      1. When: before
      2. Insert: selected (checked)
      3. Filter conditions: [Short description] [contains] [printer]
    6. Configure the Advanced section.

      1. Replace the contents of the Script field with this script.

        
            (function executeRule(current, previous /*null when async*/) {
        
                // Create a GlideRecord object  
                var grUser = new GlideRecord('sys_user');
        
                // get printer contact User record  
                grUser.get('PASTE_USER_SYS_ID_HERE');
        
                // Create message to add to the description  
                var msg = current.description + "\n\nThis incident includes 'printer' in the Short description. If you need assistance from the leasing company, contact " + grUser.name + " by email at " + grUser.email + " or by phone at " + grUser.phone + ".";
        
                current.setValue('description',msg);
        
            })(current, previous);
        
        

        NOTE: The focus of this post is on how to use the get() method and you use a hard-coded Sys ID here. Hard-coding a Sys ID in a script is not recommended because hard-coded Sys IDs are difficult to manage. Instead, use Application Properties to identify specific records. To learn more about Application Properties, go through the Application Properties training.

      2. Replace the text PASTE_USER_SYS_ID_HERE with the Sys ID copied previously.

    7. Click the Submit button.

  4. Test the Business Rule.

    1. Create an Incident with printer in the Short description field.

      1. Use the Application Navigator to open Incident > Create New.
      2. Configure the incident.
        1. Caller: Adela Cervantsz
        2. Short description: The printer is not collating
        3. Description: Network printer is printing pages out of order.
      3. Click the Additional actions button and select the Save menu item.
      4. Review the Description. The Description should now contain the text “This incident includes ‘printer’ in the Short description. If you need assistance from the leasing company, contact Printer Contact by email at pc@zeerocks.com or by phone at (212) 987-6789.”

      QUESTION: If you used a GlideRecord query instead of get, how would the Business Rule script differ? If you are not sure, scroll to the Answers section at the bottom of this page.

Challenge - Create a Business Rule to Get Patent Attorney Contact Details for NeedIt Record

Create a Business Rule for the NeedIt application from the Developer Portal training that adds contact information for the company patent attorney to the Description if the Request type is Legal and the Short description contains the word patent. The Business Rule should not overwrite the existing Description.

Starting tips:

  • Prepare the instance with the NeedIt application using the directions in Exercise: Prepare Instance for Server-side Scripting.
  • Create a User record for the patent attorney.
  • Create the Business Rule for the NeedIt table.
  • Bonus: If you are familar with Application Properties and want a little more of a challenge, create an Application Property to identify the patent attorney and use the value of the Application Property in your script.

If you need help with the script, see the Answers section at the bottom of this post for a sample script.

Create a Business Rule to Check If User is the Caller on Any Other Incidents

The GlideRecord get() method accepts two parameters. The first is the field to search and the second is the search value. If only one parameter is passed, the get() method searches by Sys ID.

Even when you are not looking to get a specific value, the get() method can be used to check for the existence of a record that matches the search criteria. The get() method returns true if it finds a record matching the specified criteria and false if no records match.

In this section, you create a Business Rule that checks if the Caller on an incident has ever opened an incident and writes an info message based on the result.

  1. Create a Business Rule.

    1. Use the Application Navigator to open Incident > Open.
    2. Click any column header menu and select the Configure > Business Rules menu item.
    3. Click the New button.
    4. Configure the Business Rule.
      1. Name: New Caller Message
      2. Advanced: selected (checked)
    5. Configure the When to run section.
      1. When: before
      2. Insert: selected (checked)
    6. Configure the Advanced section.

      1. Replace the contents of the Script field with this script.

        
            (function executeRule(current, previous /*null when async*/) {
        
                // Create a GlideRecord object  
                var grUser = new GlideRecord('incident');
        
                // get Caller User record  
                var oldCaller = grUser.get('caller_id',current.caller_id);
        
                // Initialize msg
                var msg = "";
        
                // Create message to add to an info message  
                if (oldCaller){
                    msg = current.caller_id.name + " was the caller on at least one other incident.";
                } else {
                    msg = "Incident " + current.number + " is " + current.caller_id.name + "'s first incident. Make it a good experience!";
                } 
        
                gs.addInfoMessage(msg);
        
            })(current, previous);
        
        
      2. Review this script. How does it check if a user was the Caller on an incident before?

    7. Click the Submit button.

  2. Test the Business Rule.

    1. Identify a user who has not been a caller on any incidents.
      1. Use the Application Navigator to open Incident > All.
      2. Find incidents with Abraham Lincoln as the Caller.
      3. Delete any incidents with Abraham Lincoln as the Caller.
    2. Create an Incident for a new Caller.

      1. Use the Application Navigator to open Incident > Create New.
      2. Configure the incident.
        1. Caller: Abraham Lincoln (Use a different name if Abraham Lincoln was the Caller on another incident)
        2. Short description: Mobile phone service issues
      3. Click the Submit button.
      4. Review the info message.

        An info message states Incident INC0010034 is Abraham Lincoln's first incident. Make it a good experience!

    3. Create and submit another incident for Abraham Lincoln. The info message should the Caller has other incidents.

      An info message states Abraham Lincoln was the caller on at least one other incident.

Did you do the hands-on exercise in this blog? Click here to let us know!

Closing Thoughts

The GlideRecord get() method is a useful coding shortcut when you know exactly what record you want and can uniquely identify that record. get() is also useful for quick checks to see if any records match a single query parameter.

Answers

Question: If you used a GlideRecord query instead of get, how would the Business Rule script differ?

Answer: The script would require more steps with query instead of a get:


    (function executeRule(current, previous /*null when async*/) {

        // Create a GlideRecord object  
        var grUser = new GlideRecord('sys_user');

        // Add query printer contact User record  
        grUser.addQuery('sys_id','PASTE_USER_SYS_ID_HERE');

        // You might limit to a single result, in case others are found
        grUser.setLimit(1);

        // Run query
        grUser.query();

        // Get the next record
        grUser.next();

        // Create message to post to a comment  
        var msg = current.description + "\n\nThis incident includes 'printer' in the Short description. If you need assistance from the leasing company, contact " + grUser.name + " by email at " + grUser.email + " or by phone at " + grUser.phone + ".";

        current.setValue('description',msg);

    })(current, previous);


Challenge: Here is an example script for a Business Rule that gets the patent attorney User record and adds information to the description. Replace PASTE_USER_SYS_ID_HERE with the Sys ID for your patent attorney record.


    (function executeRule(current, previous /*null when async*/) {

        // Create a GlideRecord object  
        var grUser = new GlideRecord('sys_user');

        // get printer contact User record  
        grUser.get('PASTE_USER_SYS_ID_HERE');

        // Create message to post to a comment  
        var msg = current.description + "\n\nThis Legal NeedIt request includes 'patent' in the Short description. If you need assistance from the patent attorny, contact " + grUser.name + " by email at " + grUser.email + " or by phone at " + grUser.phone + ".";

        current.setValue('description',msg);

    })(current, previous);

If you created an Application Property, your script would look similar to this:


    (function executeRule(current, previous /*null when async*/) {

        // Create a GlideRecord object  
        var grUser = new GlideRecord('sys_user');

        // get printer contact User record  
        var attorneyID = gs.getProperty('x_58872_needit.patentAttorneyID'); // Your property name may differ
        grUser.get(attorneyID);

        // Create message to post to a comment  
        var msg = current.description + "\n\nThis Legal NeedIt request includes 'patent' in the Short description. If you need assistance from the patent attorny, contact " + grUser.name + " by email at " + grUser.email + " or by phone at " + grUser.phone + ".";

        current.setValue('description',msg);

    })(current, previous);


Comments