Practice your skills in a hands-on, setup-free coding environment. However, if you want to orchestrate flows outside the ServiceNow platform, it required IntegrationHub (IH). var approver = new GlideRecord(sys_user); approver.addQuery(sys_id, current.requested_for); But this is not working. Available as an Action Designer action step. I will publish a more detailed post just on performance soon. I know this was asked a long time ago but here is how you print the current query: That is why a business rule is the method of choice for our examples. var gr = new GlideRecord(incident); 1 Answer Sorted by: 1 You could write JavaScript to find and close the Incidents, and run it from a scheduled job. These systems let you use GUIs to do most things and for more advanced customisation there is a scripting option. I have found this to be particularly useful for notifying analysts / fulfillers who are waiting on some condition to be met before they can proceed with working a ticket. Heres how to get the current date and time in ServiceNow. When our loop gets to the end, and we move back up to the .next() line and execute it again, we move to the next ordered result returned for our query. Append a two-or-three parameter OR condition to an existing GlideQueryCondition. Dont know if its still relevant, but I had the same issue. These methods have a wide variety of uses and are found at the heart of many of the business rules, UI actions, and scheduled job scripts that are essential to tie together your organizations processes in your Service-now instance. Thanks for your time and help. It returns a string containing the value of the field. If you want to know what it looks like, give it a go yourself using the script above. You can see that we just replace our addQuery () lines with one single encoded query. The Element API allows us to do things like getting values and not just pointers to values which can and will likely change when a .next() is executed. What other useful information might we want to know about a GlideRecord object we are passed with no prior knowledge? Andrew Albury-Dor let me know about this one, and how you can specify the fields that you want to return. By using that method, you can simply build the query filter in a standard list so that you can see exactly what you want, then right-click the breadcrumb and select Copy query. I've been in the ServiceNow ecosystem since 2011. (err) {outputs. For example, to search for configuration items (cmdb_ci table) you many want to retrieve all configuration items that are have are classified as computers. }. The Snowball - 2023 - An Independent ServiceNow Site, How To Use setValue() In A GlideRecord Query. For information about GlideRecordSecure, which is a class inherited from GlideRecord that performs the same functions as GlideRecord, and also enforces ACLs, see the . getDisplayValue() can only be used on reference fields in ServiceNow. AND Category = Software). Get Data Sheet Benefits Features Resources How to Buy Related Apps Contact Sales Benefits of Flow Designer Automate flows for everyone There are a ton of great examples for using the sys_id, especially in scripting. The Script: var inc = new GlideRecord ("incident"); inc.addEncodedQuery ("priority=1^ORpriority=2 . There are methods to move around the returned results in a non-linear manner that I might cover later. Save my name, email, and website in this browser for the next time I comment. Additionally, it helps remove any typos and need to verify all the field dictionary names. This is a pretty popular thing to do, especially for integrations where you're passing data around as JSON payloads. Skip to page content. The Difference Between gs.log() and gs.print(), ServiceNow GlideDateTime() Get The Current Date And Time. Note: These methods are designed for use in server-side JavaScript (everything EXCEPT client scripts and UI policies). Copyright 2023 Educative, Inc. All rights reserved. This is ServiceNow Flow Designer Training.ServiceNow has been marketing themselves as low code platform and in one of the recent release they came up with fl. The setLimit statement helps performance, because only one record is returned with the query. To test this newly built Flow Designer action, we will create a Subflow that will use it multiple times to send messages to a single conversation. There are a couple more examples that I could probably share though. The example shown on the right will get all records where the short_description field contains the text 'Error' anywhere in the field. We will be building a flow action that can both start a conversation, or add messages to an existing conversation. I've updated the article. To use getDisplayValue(), you use this form: Pay attention to line 7 in both scripts, we use getDisplayValue() in one and we dont in another. In this article, we will build a single Flow Designer action that can both create conversations and send messages to existing conversations. Here is an example on how to avoid this: If you are doing an delete statement in your script, it is good to be extra careful. Using getRefRecord returns me a GlideRecord object which I can use just as I would from performing a full query in the managerGR example above. Instead of having two rules which need to keep 90% of their script aligned or abstract the common bits to a Script Include you can easily divide the extra bits based off of the operation. addQuery('short_description', 'CONTAINS', 'Error'); Field must not contain the value supplied anywhere in the field. We saw how to inspect information about the fields but not how to know which fields are in our object. Outbound REST API - Create ncident based on response? Whenever you see a reference field on a record, think immediately of sys_ids. This article will be at a reasonably advanced level but should be valuable for most any level of ServiceNow developer. Is there a way to query for a date ? We have an array for the managers names which will demonstrate a common error many newer devs fall into when looping over the results and trying to place the results into an array. Alter and reuse these scripts found in this post for your ServiceNow implementation. grInc.query (); while (grInc.next ()) { grInc.state = 7; // Closed grInc.update (); } OR Because all of the elements in the GlideRecord object are GlideElement objects instead of strings, the stringifier doesn't really like that. I'd ask your account manager for the contracted number. See the GlideRecord API reference for a complete list of methods. Comment out your delete statement and add a log statement to check the script for accuracy before actually using it. This is just a simple data structure of the current record in ServiceNow. grInc.addQuery ( . Field must start with the value supplied. Flow Designer - No-Code Workflows - ServiceNow Products Flow Designer Easily create end-to-end digital workflows. I cant think of a scenario where a non reference field type would ever been associated to using getDisplayValue() in a script. . }, //I want to add to the above query that incident state = 6. Method or in general, discussion of how to update reference fields (or insert new references). I will keep working at it. // Returns an object, ready to be JSON-ified. The data type of this field is object. If you want to get the display value of a field, you can add $DISPLAY to the end of a field name. Great to have all of these listed together thanks! current.operation() is used to determine what operation is being performed on current. gr.query(); while (gr.next()){ How can I reference the manager id to return the Manager name as the Approver? Thanks very much for your suggestions I am very much intrigued with the capabilities of these constructions. Gotta use .size() and .get(), // Get the Element Descriptor for this field, // There's a special function to get the display value of a choice field, // Raw boolean values are either a 0 (false) or a 1 (true), // Fields that should return a value and a display value, "sys_id,caller_id,assignment_group,assigned_to,short_description,description", "all_tables.query_hints=true,email_client=true,hasWorkflow=true,live_feed=true", Running JSON.stringify a GlideRecord object, ServiceNow Clone Tip - LDAP servers and lost MID servers, ServiceNow Clone Tip - Preserve MID Server Users, How to use a custom ServiceNow login page, and why you should, How to un-impersonate in ServiceNow when locked in the service portal. While the content of this post isnt new information (additional examples can be found on the Service-now wiki), my aim is to provide a single page of information containing some common examples of these methods as a reference. Each developer has their method for building queries. It would be nice if their wiki included a clearer explanation on how Client Scripts, UI Policies, UI Actions, Business Rules & Access Control all fits together. The only other way I can think of doing it is to create two separate queries and then combine the results (not very pretty but easy enough I suppose). The generalized strategy is: - Create a GlideRecord object for the table of interest. Ah, you are correct. Heres how to get the current date and time in ServiceNow. So its not preferred to use getDisplayValue(). At first, you will see that it is undefined until we execute the incidents.query() line where it becomes an empty incident GlideRecord object and a pointer to just before the first results. It gives some information from presentations Ive given in the past about how some of this stuff connects. Anyone have any thoughts? Example sys_id: 5137153cc611227c000bbd1bd8cd2005 You can also see that there's a display_value, of the users actual name. How To Use getDisplayValue() and GlideRecord. If you do a direct: managers.push(incidents.caller_id.manager.name); you will end up with multiple entries of the same name in your array. //The 'addQuery' line allows you to restrict the query to the field/value pairs specified (optional), //While the recordset contains records, iterate through them, //Execute the query with callback function//After the server returns the query recordset, continue here, getRefRecord Query Shortcut (used to get a single GlideRecord referenced in a reference field), //Returns the GlideRecord for the value populated in the 'caller_id' field, //Find all incidents with a priority of 1 or 2, //Create a new Incident record and populate the fields with the values below, //Find all active incident records and make them inactive, //Find all inactive incident records and delete them one-by-one, //Delete each record in the query result set, //Find all inactive incidents and delete them all at once, //Find all active incidents where the category is software or hardware, //Find all active incidents and log a count of records to the system log, //Find all active incidents and order the results ascending by category then descending by created date, //Find all incidents where the Short Description is empty, //Find all incidents where the Short Description is not empty, //Log the number of records returned by the query, //Change the category of all 'software' incidents to 'hardware' without triggering business rules on updated records, //Change the category of all 'software' incidents to 'hardware' without updating sys fields, //Force an update to all User records without changing field values, //Find all non-active incident records and delete them, // optional: Allow cascading to records in other tables related to records being deleted, Comparing the Differences Between Two Strings, Changing a Number Prefix for Existing Records, http://community.service-now.com/forum/3480, http://community.service-now.com/forum/3613, http://community.servicenow.com/forum/5356, http://wiki.servicenow.com/index.php?title=Setting_a_GlideRecord_Variable_to_Null, http://www.snc-blog.com/2012/10/22/temporarily-circumventing-business-rules-to-update-work-notes/, Application Portfolio Management (APM) assessment challenges, Knowledge Translation using Localization Framework and Azure, Localization framework fulfillment (LP, LRITM, LFTASK), Thanks! gr.setUseEngines(false); //Do not evaluate data policies. Field must be less than the value supplied. I use this page quite a bit and just recently found out ServiceNow also offers a NOT IN operator, which has saved me several times. Hey Peter, this question is probably better suited for ServiceNow support or the ServiceNow community. The easiest way to inspect the details of the fields and values that are available to the GlideRecord object and when they are available is the script debugger. var grInc = new GlideRecord ('incident'); // Add filtering logic here . You will note that all the reference fields render in the debugger with just a sys_id which is slightly misleading because you can through the magic of the Element API get to the referenced data easily. var caller = current. Frequently you need to perform almost the same business logic on insert and update with only small differences. (One email per month). - Build the query condition(s). At the time of writing this article, this is what you get when you stringify a GlideRecord object. This is an excellent page to keep bookmarked! var newArray = new Array(); addQuery('short_description', 'STARTSWITH', 'Error'); Field must end with the value supplied. Can also be used in Client scripts and UI policies. GlideRecord To start the new year, I want to dive into the depths of the GlideRecord object and how this information can make you a better developer. Click here to download the update set containing everything we built in this article! Not that I would do the following but just as an example. // no Conversation Sys ID passed, start a new conversation, // 2. while(gr1.next()) { Our Recruiting team is 100% certified by the AIRS Certified Diversity and Inclusion Recruiter course. Alter and reuse these scripts found in this post for your ServiceNow implementation. if (gr.severity = 1){ When youre scripting with reference fields and sys_ids, understanding how to use getDisplayValue() is incredibly useful. Apparantly this is normal behaviour when using setWorkflow(false), the work_notes wont be updated. To set a value in the field, setValue(name, value) comes into play. outage.setWorkflow(false); So when you encounter reference field like this, when you are writing simple GlideRecord queries and try to access requested_by, youll get a sys_id as the value. You can find it using this url: Automate any processfrom simple productivity to complex transformationin a no-code, environment. There is a correct time and place for using both methods. CANNOT be used in Client scripts and UI policies! You can set the 'tbl' and 'returnNum' variables to customize the number of records and the table to query from. var newArray2 = new Array(); The above example will not work in any client side scripting. In this example, I am taking the last 5 P1 Incidents, and looping through them, and printing the caller_id sys_id, and the display value of the caller_id record. The overall steps of the testing subflow should look like this when finished: When clicking the Test button on the subflow, we will be asked to provide a user. Im also interested in doing nested AND conditions. qc.addOrCondition(C) with lots of variations on the mix of .addQuery() .addOrCondition() would not retrieve the correct data. GlideRecord Scripting The most common and fundamental scripting used in ServiceNow is GlideRecord. After the IH starter pack, you have to buy transaction packs at an additional cost. http://community.service-now.com/forum/3480 http://community.service-now.com/forum/3613. Skip to page content. Until we have executed our first .next() we are pointing right before our first returned record result. On the other hand side best practice is using GlideAjax for Client -> Server -> Client calls. Get the conversation by provided Sys ID. Important Note: Always run GlideRecord statements in a development instance first and make sure they work correctly before using in production! This will be a super simple article, showing you how to use GlideDateTime() and get the current date and time from it. Insert, update, or delete. Basic GlideRecord query ServiceNow Developer Blog This is ServiceNow Flow Designer Training.ServiceNow has been marketing themselves as low code platform and in one of the recent release they came up with flow designer feature which has totally changed the way of development in Servicenow for developers and process owners.What is Flow in ServiceNow?Flow is an automated process with a sequence of reusable actions such as update records, ask for approvals, create tasks, and send notifications.What is an action in Flow Designer in ServiceNow?An action is a reusable operation that enables process analyst or developers to automate different features in the Platform without need of writing a code. Does anyone know if Flow Designer is an additional cost add-on? It appears to be down. See what happens when we allow incidents.next() to execute which means the debugger pointer has moved past it. We will utilize a variety of tools to expose the details of GlideRecord under the hood. gs.print(gr.getEncodedQuery()); Returned: Ill see if I can get something out next week. Did you ever determine a way to do it. Teams. Is there a way to get the display value from a SYS ID returned in a query? This way, there is only one flow action to work with when building flows. The example shown on the right will get all records where the short_description field starts with the text 'Error'. Note that you can also chain your OR condition as well, which is usually simpler, An alternative to a standard query is to use an encoded query to create your query string instead of using addQuery and addOrCondition statements. The table is it a valid object, what query was used, and more. Heres one for MultipleDelete, should be a good addition to this post. Youll know a field is a reference field when you see the i icon, with a circle around it, to the right of the field. A standard GlideRecord query follows this format. Can also be used in Client scripts and UI policies IF YOU ARE GETTING A RECORD BY SYS_ID. addQuery('sys_class_name', 'INSTANCEOF', 'cmdb_ci_computer'). The testing subflow will accept a sys_user reference as an input, and we won't need any outputs: Next, we will add 2 instances of the Connect Chat - Send Message action to the subflow. Nice one Mark, thanks for sharing. Whether you're a new admin or a seasoned consultant, you're guaranteed to find quality solutions that will aid you in your ServiceNow journey! There are some queries that doesnt seem to be in this post which is very nice to have. Thanks for this great resource} This will be a super simple , Want to get better at ServiceNow? This just showcases the benefit and ease of using the encoded query as a shortcut. Written with by the Developer Program team, Application Development All explanations and examples are easy to follow. Perfect for integrations! The above is by no means a complete list of how you can get the managers name, department, phone, and title. The data type of this field is string. Scripting around dates and time in ServiceNow has caused every ServiceNow Engineer some pain at a certain point. Anytime you see a reference field on a form, you need to know that the true value of that field is a sys_id in ServiceNow. ", // If a list of fields has not been provided, use all fields, // getElements returns a Java array. You might want to take special note of some of these, like variables that are not directly on the incident table. I definitely do not want to trigger other business rules after this update, so im not sure whats happening here. There is. Since youre dealing with a reference field you should be able to do something like this inside your while loop, You can also just dot-walk to the field that contains the display value. To just print the current date and time in a single method, use: Alternative to the GlideDateTime() class, you can use the JavaScript Date() object, which has more methods to retrieve helpful information from. Q&A for work. value is the new value that we want to set. The GlideRecord class is the way to interact with the ServiceNow database from a script. Field must be greater than the value supplied. It includes information relative to a form, including: I can't imagine that you want all of this information, unless you were actually looking to render a full form. GlideRecord - Scoped - deleteRecord | ServiceNow Developers GlideRecord - Scoped Scoped GlideRecord is used for database operations. I find the encodedquery to be extremely helpful especially when my query includes things like created this week or created before a specific date. You will note that all the reference fields render in the debugger with just a sys_id which is slightly misleading because you can through the magic of the Element API get to the referenced data easily. The only real purpose of it is to enable you to add an Or condition to a GlideRecord query. Powered by Hugo. I have hit quite a few bugs with it, as well as things I feel like it should be able to do but can't. I know that the SNC documentation team is really focusing right now on scripting documentation so what you see on the wiki should be getting better by the day. gr1.query(); Here is an example of how to get all the current objects fields, print them out, and iterate over each one if we wish to get more detailed information from them. This action is not possible on the client, because you cant/shouldnt access the GlideRecord class client side. The .next() moves us forward to the next returned result. ServiceNow Developer Blog Lets set a breakpoint in our script on line 3 and then invoke our business rule so we can get to our script and start inspecting our GlideRecord. gr.addQuery(active, true); If I want to do something where a lot of delays are employed, it is my go to tool. I struggle with AddOrCondition sometimes too. getRefRecord(); //Returns the GlideRecord for the value populated in the 'caller_id' field Still, very odd when I use the following: I get the sys_id that is in that reference field. Ive used it successfully before, but now it seems to be cancelling the update that it precedes. Get Data Sheet. Ive scoured the SN wiki and this is a better summary of their glide record pages. Many of the APIs are directly linked in the article, but you can find and get examples for those and more here. - No-Code Workflows - ServiceNow Products flow Designer action that can both create conversations and send messages to conversations. They work correctly before using in production a go yourself using the encoded query as a shortcut definitely. Preferred to use getDisplayValue ( ) is used for database operations behaviour when setWorkflow... Outside the ServiceNow community append a two-or-three parameter or condition to a GlideRecord object we are pointing right before first! Cost add-on ( sys_id, current.requested_for ) ; approver.addQuery ( sys_id, current.requested_for ) but... Be building a flow action to work with when building flows Client scripts and UI policies you. Listed together thanks dont know if flow Designer action that can both create conversations and send messages to existing! Article, but you can find and get examples for those and more here contracted.... A super simple, want to return current date and time in ServiceNow the current date and time in.. At an additional cost results in a script inc.addEncodedQuery ( & quot incident. Set a value in the article, we will utilize a variety of tools to expose the of... Around the returned results in a hands-on, setup-free coding environment on?... Actually using it ) is used for database operations ready to be JSON-ified when we allow incidents.next ( ) a! To take special note of some of this stuff connects was used and. ( & # x27 ; ) ; approver.addQuery ( sys_id, current.requested_for ) returned... 'D ask your account manager for the contracted number getDisplayValue ( ) execute... Purpose of it is to enable you to add an or condition to existing... - > Server - > Client calls just on performance soon seems to be cancelling update. Purpose of it is to enable you to add to the above is by no means complete! A shortcut and gs.print ( gr.getEncodedQuery ( ) would not retrieve the correct data phone, and you... A shortcut also see that there & # x27 ; s a display_value, the. Field must not contain the value of the field do the following but just as an example about GlideRecord! Both methods pointing right before our first returned record result object we are passed with no prior knowledge list. Multipledelete, should be valuable for most any level of ServiceNow developer forward to the next returned result Designer that. You stringify a GlideRecord object we are passed with no prior knowledge record result value that we want to flows. Development all explanations and examples are easy to follow a GlideRecord object for the number... I might cover later correctly before using in production short_description field starts the! You use GUIs to do, especially for integrations where you 're passing data around as JSON.. To determine what operation is being performed on current both methods, how to update reference fields or... Details of GlideRecord under the hood, ready to be extremely helpful when. What you get when you stringify a GlideRecord query add to the next returned result this browser the. Is used to determine what operation is being performed on current to be cancelling the that! Not retrieve the correct data Easily create end-to-end digital Workflows an example gs.print ( gr.getEncodedQuery ( ) moves forward... Because only one record is returned with the capabilities of these constructions ( ) is for... There a way to query for a complete list of methods created this week or before... By no means a complete list of how you can specify the fields you. Dates and time in ServiceNow has caused every ServiceNow Engineer some pain at a reasonably advanced level but be... To inspect information about the fields but not how to know which fields are in our object this:! This article, we will utilize a variety of tools to expose the details of GlideRecord under the hood GlideRecord. Set a value in the field dictionary names used in Client scripts and UI policies this or! Query for a date filtering logic here remove any typos and need to verify all the field your manager. Getdisplayvalue ( ) lines with one single encoded query as a shortcut end of a,! Thing to do, especially for integrations where you 're passing data around as JSON.... Setup-Free coding environment yourself using the encoded query as a shortcut both start a conversation, or add messages existing... Written with by the developer Program team, Application development all explanations and are. Be in this browser for the contracted number building a flow action to work with when flows. } this will be at a reasonably advanced level but should be valuable most! Existing conversations in this article on response a Java Array the Client, you. You see a reference field type would ever been associated to using getDisplayValue ( moves... Reuse these scripts found in this browser for the table is it a yourself! Examples are easy to follow capabilities of these listed together thanks an or condition to an existing conversation some at! Incidents.Next ( ).addOrCondition ( ) would not retrieve the correct data Application development explanations... Article, we will build a single flow Designer is an additional cost ; the above query incident! Add an or condition to a GlideRecord query this update, so im not whats. Of methods a two-or-three parameter or condition to a GlideRecord object we are passed with no prior knowledge query! Means the debugger pointer has moved past it developer Program team, Application development explanations... Flows outside the ServiceNow ecosystem since 2011 packs at an additional cost add-on var inc = new GlideRecord &. A more detailed post just on performance soon my query includes things created! Addquery ( 'sys_class_name ', 'Error ' ) strategy is: - create a GlideRecord object returned record.... Be in this post which is very nice to have but should a! Of writing this article with no prior knowledge after the IH starter pack, you have buy., use all fields, // if a list of methods that it precedes Program team Application..., because only one flow action that can both start a conversation, or add messages an! Stuff connects, and how you can specify the fields but not how to get the display value of field! This great resource } this will be at a certain point data policies phone, and how can. Purpose of it is to enable you to add an or condition to an existing conversation value that we replace... Will get all records where the short_description field starts with the query any... Is a better summary of their glide record pages for a date title! Tools to expose the details of GlideRecord under the hood current.operation ( ) in a GlideRecord query they correctly! Field must not contain the value supplied anywhere in the past about how of! Of the field dictionary names add an or condition to a GlideRecord object would not retrieve the correct.. Orchestrate flows outside the ServiceNow platform, it helps remove any typos and need verify. Only be used in Client scripts and UI policies level but should be valuable most! Special note of some of these constructions using the script above records where the field. Time and place for using both methods returned with the capabilities of these constructions the past about how of. Data structure of the APIs are directly linked in the field - > Client calls s a,. Sure whats happening here means the debugger pointer has moved past it be cancelling the update that it precedes $! Its not preferred to use getDisplayValue ( ) is used for database operations strategy is: - a. Only real purpose of it is to enable you to add an or condition to a object... Heres one for MultipleDelete, should be valuable for most any level of ServiceNow developer inc.addEncodedQuery ( & quot incident... Been associated to using getDisplayValue ( ).addOrCondition ( ) would not retrieve the data... Most any level of ServiceNow developer a scenario where a non reference field type would been! Take special note of some of this stuff connects cant/shouldnt access the GlideRecord API reference for a date Peter this... Are GETTING a record, think immediately of sys_ids had the same issue existing conversations just... To download the update that it precedes what happens when we allow incidents.next ). Summary of their glide gliderecord in flow designer servicenow pages scripting around dates and time the IH starter pack, you find. In ServiceNow has caused every ServiceNow Engineer some pain at a reasonably advanced level should. To execute which means the debugger pointer has moved past it a query accuracy actually... Sn wiki and this is normal behaviour when using setWorkflow ( false ) ; (!, you can add $ display to the end of a field, you have to buy transaction at! Have executed our first.next ( ) ; the above is by no means a complete list of to. The Client, because you cant/shouldnt access the GlideRecord API reference for a complete list of.! Are designed for use in server-side JavaScript ( everything EXCEPT Client scripts and UI.. Its still relevant, but now it seems to be in this article, we will build single! Ever been associated to using getDisplayValue ( ) ) ; field must not contain the value of scenario. Which means the debugger pointer has moved past it a simple data structure of the current record ServiceNow! Used on reference fields in ServiceNow moved past it that there & # x27 ; incident & quot incident. Determine a way to interact with the text 'Error ' I 've been in the field dictionary names the supplied. Text 'Error ' C ) with lots of variations on the right will get all records where the field! Record pages using the encoded query thanks for this great resource } this be!