├── .github └── workflows │ └── hacktrack.yml ├── APIs ├── CartAPI │ ├── CartApi.js │ ├── CartApi_multi.js │ └── CartJS api.js ├── IP Address │ ├── README.md │ ├── isIpv4.js │ ├── isIpv6.js │ └── isValidIp.js └── Optional API │ ├── README.md │ ├── empty.js │ ├── filter.js │ ├── flatMap.js │ ├── get.js │ ├── ifPresent.js │ ├── isEmpty.js │ ├── lazy.js │ ├── map.js │ └── orElse.js ├── CONTRIBUTING.md ├── Client Scripts ├── Confirm Msg on UI Action Click.js ├── Mandatory Fields onSubmit.js └── getReference │ ├── ReadMe.md │ ├── getReference.js │ └── script.js ├── Date Time └── convertEpochToDateTime.js ├── Error Handling ├── Error Handling.js └── README.md ├── Flow Designer ├── DataStreaminScript │ ├── code.js │ └── readme.md ├── Extract Data From Excel │ ├── code.js │ └── readme.md ├── GlideflowAPI │ ├── code.js │ └── readme.md └── flowapitocallFlow │ ├── code.js │ └── readme.md ├── General ├── ArrayFilter.js ├── arraySortEs5.js ├── arraySortEs6.js ├── for.js ├── foreach.js ├── getprop.js ├── if-else.js ├── if.js ├── map.js ├── switchcase ├── trycatch └── while.js ├── GlideAggregate ├── GlideAggregate.js ├── GlideAggregateES12 ├── GlideAggregate_GroupingIncidents_Calculate_AverageTimetoclose.js ├── glideAggregateSetAggregateWindow.js ├── glideaggregateaddtrend.js └── vargragg.js ├── GlideAjax ├── Concise way of doing a GlideAJAX call │ └── readme.md ├── ajax.js ├── ajax_client_answer.js ├── ajax_server.js ├── gajax.js ├── userDetailsAutopopulate-ScriptInclude └── userDetailsPopulation-Client ├── GlideDateTime ├── DaysUntilFutureDate.js ├── UpdatedWithinList.js └── getlocaldate.js ├── GlideEncrypter ├── Decrypter.js └── Encrypter.js ├── GlideExcelParser └── readExcelFile.js ├── GlideFilter └── caseSensitiveFilter.js ├── GlideForm ├── addDecoration ├── addOption ├── addOptionIndex └── clearOptions ├── GlideModal ├── UIPage.js ├── g_model for workspace client script └── glidemodalWithHTML.js ├── GlideQuery ├── glidequeryaggregate.js ├── glidequerydeletemultiple.js ├── glidequeryinsert.js ├── glidequeryreduce.js ├── glidequeryselect.js ├── glidequeryselectone.js ├── glidequeryupdate.js ├── glidequeryupdatemultiple.js └── glidequerywithAcls ├── GlideRecord ├── GetRecordsES12 ├── GlideFetchChildRecords.js ├── GlideRecordApplyTemplate.js ├── GlideRecordUpdateMultiple.js ├── InsertRecordES12 ├── UpdateRelatedRecords ├── applyEncodedQuery.js ├── brGlideAbortCheck ├── clonerecord ├── getRecordShortVersion ├── gliderecorddeleteget.js ├── gliderecorddeletemultiple.js ├── gliderecorddeletequery.js ├── gliderecordencode.js ├── gliderecordforceupdate.js ├── gliderecordget.js ├── gliderecordnodomain.js ├── gliderecordorchain.js ├── gliderecordtoiteratethroughallrecords.js ├── gliderecordupdateget.js ├── gliderecordupdatequery.js ├── gr-update-or-insert.js ├── groder.js ├── incidentbypriority.js ├── interatethroughonlyfirstrecord.js ├── newgr.js └── noauto.js ├── GlideRecordSecure ├── CreateOrUpdate.js ├── CreateRecord.js ├── deleteMultiple.js ├── getRecord.js ├── updateMultipleTemplate.js └── updateRecordQuery.js ├── GlideScopedEvaluator ├── glideEvaluator.js └── readme.md ├── GlideSecureRandomUtil └── GlideSecureRandomUtil.js ├── GlideSysAttachment ├── addAttachment.js └── getAttachments.js ├── GlideSystem ├── To find Specific String using Index of.js ├── addErrorMessage.js ├── addInfoMessage.js ├── dateDiffGlobal └── impersonate.js ├── GlideUser └── GlideUser.js ├── GlideUtils ├── GlideUtils Syntax Macros │ ├── GlideUtils.arrayCopy().js │ ├── GlideUtils.arrayFind().js │ ├── GlideUtils.escapeHTML().js │ ├── GlideUtils.getCallerStack().js │ ├── GlideUtils.getClassName().js │ ├── GlideUtils.getKeys().js │ ├── GlideUtils.isNil().js │ ├── GlideUtils.isNumeric().js │ ├── GlideUtils.parseInt().js │ ├── GlideUtils.xmlEscape().js │ └── README.md └── getRefRecord.js ├── HTML ├── htmlTable.js └── readme.md ├── InboundEmailActions └── Inbound Actions ├── Integration ├── restmessagesync.js └── soapmessagesync.js ├── JSON ├── JSONAdv ├── JSONSyn ├── JSON_Iterator.js └── JSON_Response_Builder.js ├── Label Styles ├── FieldBold.js └── FieldFlash.js ├── MailScript ├── Add User to CC_BCC.js ├── Portal Link │ ├── readme.md │ └── spLink.js └── getLatestComment.js ├── OutboundEmail Action └── sendOutboundEmail.js ├── README.md ├── RESTMessageV2 └── restMessageV2.JS ├── RestMessage └── rest_out.js ├── Scheduled Jobs └── User Deactivation Macro │ ├── ReadMe.md │ └── User Deactivate Job.js ├── Script Include └── To Inherit a Script Include │ └── inheritScriptInclude.js ├── Script Version Differ ├── ScriptVersionDiff.js └── readme.md ├── Script include function syntax └── siFun.js ├── Service Portal ├── Widgets │ ├── Client-Server_Request-Response.js │ └── server-template.js ├── spModal │ ├── Form Modal.js │ ├── Large Popup HTML Message.js │ └── spmodal.md ├── spOnReady │ ├── readme.md │ └── sp_onready.js └── spUtil │ ├── addErrorMessage │ ├── addInfoMessage │ ├── addTrivialMessage │ ├── format │ ├── get(String widgetId Object data) │ └── recordWatch.js ├── Sharing Data Between Widgets ├── broadcast.js └── listener.js ├── StopWatch └── stopwatch.js ├── Sub Flow ├── SubFlowClient.js └── readme.md ├── TemplatePrinter ├── README.md ├── print.js └── space.js ├── UI Action ├── README.md └── gsftSubmit.js ├── VSCode ├── README.md ├── grwhile.js ├── newlog.js ├── tblplt.js ├── tblplts.js └── vsga.js ├── Validation Messages ├── README.md └── returnChecks.js ├── eslint ├── README.md ├── eslint ├── eslintDisableBlock ├── eslintDisableLine ├── eslintDisableNext └── eslintEnableBlock └── snDoc ├── README.md └── snDoc.js /.github/workflows/hacktrack.yml: -------------------------------------------------------------------------------- 1 | #This file is for ServiceNow Dev Program Hacktoberfest Tracking and can be ignored or deleted. 2 | 3 | name: Record Hacktrack Event 4 | on: 5 | push: 6 | branches: main 7 | fork: 8 | branches: main 9 | issues: 10 | types: [opened, closed] 11 | branches: main 12 | pull_request_target: 13 | types: [opened, closed] 14 | branches: main 15 | jobs: 16 | deployment: 17 | if: github.repository == 'ServiceNowDevProgram/syntax_macros' 18 | runs-on: ubuntu-latest 19 | steps: 20 | # - name: Log payload 21 | # env: 22 | # GITHUB_CONTEXT: ${{ toJson(github) }} 23 | # run: | 24 | # echo "$GITHUB_CONTEXT" 25 | - name: Contact DPR 26 | id: myRequest 27 | uses: fjogeleit/http-request-action@v1.8.1 28 | with: 29 | url: ${{ format('https://{0}.service-now.com/api/x_snc_hacktrack/hacktrack', secrets.HT_INSTANCE_NAME) }} 30 | method: 'POST' 31 | contentType: application/json 32 | data: ${{ toJson(github) }} 33 | username: ${{ secrets.ADMIN_USERNAME }} 34 | password: ${{ secrets.ADMIN_PASSWORD }} 35 | - name: Show Response 36 | run: echo ${{ steps.myRequest.outputs.response }} 37 | -------------------------------------------------------------------------------- /APIs/CartAPI/CartApi.js: -------------------------------------------------------------------------------- 1 | //generate a cart and insert an RITM 2 | 3 | var cart = new Cart(); 4 | var RITM = cart.addItem('sysid of cat item'); 5 | cart.setVariable(RITM, 'variable name', 'value'); // setting variables, copy paste this line for multiples 6 | var request = cart.placeOrder(); // this returns the sysid of the top-level request 7 | -------------------------------------------------------------------------------- /APIs/CartAPI/CartApi_multi.js: -------------------------------------------------------------------------------- 1 | //generate a cart and insert an RITM, for additional RITMs, copy line 7 & 8 as needed 2 | 3 | var cart = new Cart(); 4 | var RITM = cart.addItem('sysid of cat item'); //first ritm 5 | cart.setVariable(RITM, 'variable name', 'value'); // setting variables, copy paste this line for multiples 6 | 7 | var RITM2 = cart.addItem('sysid of cat item'); //second ritm 8 | cart.setVariable(RITM2, 'variable name', 'value'); // setting variables, copy paste this line for multiples 9 | 10 | var request = cart.placeOrder(); // this returns the sysid of the top-level request 11 | -------------------------------------------------------------------------------- /APIs/CartAPI/CartJS api.js: -------------------------------------------------------------------------------- 1 | //use this when trying to create a request within a scoped app 2 | 3 | var cart = new sn_sc.CartJS(); // CartJS uses a JSON object to capture item and variables 4 | var item = { 5 | 'sysparm_id': 'actual-sys-id', // replace with actual sys ID 6 | 'sysparm_quantity': '1', 7 | 'variables': { 8 | 'variablename1': 'value', //the duplicates have been resolved here 9 | 'variablename2': 'value' 10 | } 11 | }; 12 | 13 | try{ 14 | var cartVals = cart.addToCart(item); // this will return a JSON object 15 | var checkoutVals = cart.checkoutCart(); // this will also return a JSON object containing information about the submitted cart 16 | } 17 | catch(error) 18 | { 19 | console.log('Error', error); 20 | } 21 | -------------------------------------------------------------------------------- /APIs/IP Address/README.md: -------------------------------------------------------------------------------- 1 | This API provides various methods to check for various states of a specified IP address. 2 | -------------------------------------------------------------------------------- /APIs/IP Address/isIpv4.js: -------------------------------------------------------------------------------- 1 | //Verifies to ensure that the given IP address is a valid IPv4 address. 2 | 3 | var ip = "192.168.1.1"; 4 | gs.info("ip address is v4?: " + new IPAddress(ip).isV4()); 5 | -------------------------------------------------------------------------------- /APIs/IP Address/isIpv6.js: -------------------------------------------------------------------------------- 1 | //Verifies to ensure that the given IP address is a valid IPv6 address. 2 | 3 | var ip = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; 4 | gs.info("ip address is v6?: " + new IPAddress(ip).isV6()); 5 | -------------------------------------------------------------------------------- /APIs/IP Address/isValidIp.js: -------------------------------------------------------------------------------- 1 | //Determines whether the specified IP address is a valid IPv4 or IPv6 address. 2 | 3 | var ip1 = "192.168.1.1"; 4 | gs.info("ip1 address is valid?: " + new IPAddress(ip1).isValid()); 5 | 6 | var ip2 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334"; 7 | gs.info("ip2 address is valid? " + new IPAddress(ip2).isValid()); 8 | -------------------------------------------------------------------------------- /APIs/Optional API/README.md: -------------------------------------------------------------------------------- 1 | The Optional API interacts with a single record returned by the GlideQuery, Stream, or GlideRecord APIs, even when it does not exist. Write scripts that are less likely to result in an error by handling null or undefined query results. 2 | -------------------------------------------------------------------------------- /APIs/Optional API/empty.js: -------------------------------------------------------------------------------- 1 | /* 2 | empty(String reason) 3 | Returns an empty Optional object. Use this method in an Else clause to handle a query that might not return a result. 4 | 5 | */ 6 | 7 | var now_GR = new GlideRecord('task'); 8 | now_GR.addQuery('approval', 'not requested'); 9 | now_GR.query(); 10 | var optional; 11 | if (now_GR.next()) { 12 | optional = Optional.of(now_GR.getUniqueValue()); 13 | } else { 14 | optional = Optional.empty("no results"); 15 | } 16 | 17 | gs.info(optional.get()); 18 | -------------------------------------------------------------------------------- /APIs/Optional API/filter.js: -------------------------------------------------------------------------------- 1 | /* 2 | filter(Function predicate) 3 | Applies a predicate function, a function that takes a single value and returns true or false, to the record inside the Optional object. If the function returns true, the method returns the Optional record unchanged. If the function returns false, it returns an empty Optional object. 4 | 5 | */ 6 | 7 | var filteredQuery = new global.GlideQuery('sys_user') 8 | .getBy({ sys_id: 'f682abf03710200044e0bfc8bcbe5d38' }, ['phone']) 9 | .filter(function (user) { 10 | return phoneRegex.test(user.phone); 11 | }); 12 | -------------------------------------------------------------------------------- /APIs/Optional API/flatMap.js: -------------------------------------------------------------------------------- 1 | /* 2 | flatMap(Function fn) 3 | Applies a function that returns an Optional object to the result of a query. Use this method to perform a second query using the result of the first. 4 | 5 | */ 6 | 7 | 8 | new global.GlideQuery('alm_asset') 9 | .whereNotNull('owned_by') 10 | .selectOne('owned_by') 11 | .flatMap(function (asset) { 12 | return new global.GlideQuery('sys_user') 13 | .getBy({ sys_id: asset.owned_by }, ['first_name', 'last_name', 'company.name']) 14 | }) 15 | .ifPresent(GQ.jsonDebug); 16 | -------------------------------------------------------------------------------- /APIs/Optional API/get.js: -------------------------------------------------------------------------------- 1 | /* 2 | get() 3 | Returns the record inside the Optional object, or throws an error if the query does not return a record. 4 | 5 | */ 6 | 7 | 8 | var value = new global.GlideQuery('sys_user') 9 | .selectOne('first_name') //Returns the result of the query inside an Optional object 10 | .get(); //Calls Optional.get() on the Optional object 11 | 12 | gs.info(JSON.stringify(value)); 13 | -------------------------------------------------------------------------------- /APIs/Optional API/ifPresent.js: -------------------------------------------------------------------------------- 1 | /* 2 | ifPresent(Function fn) 3 | Applies a function to the record within an Optional object. If the Optional object does not contain a record, the function does not execute. 4 | 5 | */ 6 | 7 | 8 | var user = new global.GlideQuery('sys_user') 9 | .where('sys_id', 'f682abf03710200044e0bfc8bcbe5d38') 10 | .selectOne('zip') 11 | .ifPresent(function (user) { 12 | gs.info('Zip Code: ' + user.zip); 13 | }); 14 | -------------------------------------------------------------------------------- /APIs/Optional API/isEmpty.js: -------------------------------------------------------------------------------- 1 | /* 2 | isEmpty() 3 | Returns true if the Optional object is empty. 4 | 5 | */ 6 | 7 | 8 | var checkEmpty = new global.GlideQuery('sys_user') 9 | .where('last_name', 'Barker') 10 | .selectOne() 11 | .isEmpty(); 12 | 13 | gs.info(checkEmpty); 14 | -------------------------------------------------------------------------------- /APIs/Optional API/lazy.js: -------------------------------------------------------------------------------- 1 | /* 2 | lazy(Function lazyGetFn) 3 | Returns a new Optional object. Instead of containing the record, the object contains a function to get the record that is only called if and when requested in the code. 4 | Use this method to delay getting the value until it's needed. You might do this if requesting the value from a slow source and don't want to slow down your code unnecessarily. Otherwise, you can return an Optional object using the GlideQuery and Stream APIs. 5 | 6 | */ 7 | 8 | 9 | var userOptional = global.Optional.lazy(function () { 10 | var userGr = new GlideRecord('sys_user'); 11 | userGr.setLimit(1); 12 | userGr.query(); 13 | return userGr.next() ? userGr.getUniqueValue() : null; 14 | }); 15 | 16 | gs.info(userOptional); 17 | -------------------------------------------------------------------------------- /APIs/Optional API/map.js: -------------------------------------------------------------------------------- 1 | /* 2 | map(Function fn) 3 | Applies a function to the result of a query. 4 | */ 5 | 6 | 7 | var value = new global.GlideQuery('sys_user') 8 | .whereNotNull('first_name') 9 | .selectOne('first_name') 10 | .map(function (user) { 11 | return user.first_name.toUpperCase(); 12 | }); 13 | 14 | gs.info(value); 15 | -------------------------------------------------------------------------------- /APIs/Optional API/orElse.js: -------------------------------------------------------------------------------- 1 | /* 2 | orElse(Any defaultValue) 3 | Adds a default value within the Optional object if the query does not return any results. 4 | 5 | */ 6 | 7 | 8 | var user = new global.GlideQuery('sys_user') 9 | .get('1234', ['first_name', 'last_name']) 10 | .orElse({ first_name: 'Default', last_name: 'User' }); 11 | 12 | gs.info(JSON.stringify(user)) 13 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## General requirements 4 | 5 | - Pull request descriptions must be explicit and descriptive to what is being changed. 6 | - Changes that are not within the scope of the description will result in the entire PR being rejected 7 | - Low effort/spam Pull Requests will be marked as spam accordingly. 8 | - Do not add files to the root directory of this repository. 9 | 10 | ## Process 11 | 12 | 1. Fork this repo 13 | 2. Create a new branch (name it according to what functionality you are adding) 14 | 3. Add/update folders and files on your branch 15 | 5. Submit a pull request to the ServiceNowDevProgram/syntax_macros `main` branch 16 | -------------------------------------------------------------------------------- /Client Scripts/Confirm Msg on UI Action Click.js: -------------------------------------------------------------------------------- 1 | //This onSubmit client script will produce a popup confirm message when a UI action is clicked. 2 | //Use cases are when deleting a record or require a confirmation before the UI action is completed. 3 | 4 | function onSubmit() { 5 | var action = g_form.getActionName(); 6 | var answer; 7 | 8 | if (action == "UIACTIONNAME") { 9 | answer = confirm(getMessage("Are you sure you want to delete this record?")); 10 | if (answer != true) 11 | return false; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Client Scripts/Mandatory Fields onSubmit.js: -------------------------------------------------------------------------------- 1 | //This is an onSubmit client script to make fields mandatory when a UI action is clicked. Ideally use a UI policy if possible. 2 | //However this use case is to allow the user to save the form if the data can't be filled in presently or is awaiting information. 3 | 4 | function onSubmit() { 5 | g_form.clearMessages(); 6 | var action = g_form.getActionName(); 7 | var error = false; 8 | var errorFields = []; 9 | var mandFields = []; 10 | 11 | switch (action) { 12 | case "ui_action_name": 13 | mandFields = ['reviewing_group', 'assessors', 'description']; 14 | break; 15 | case "ui_action_name_2": 16 | mandFields = ['outcome', 'close_notes']; 17 | } 18 | 19 | for (var index = 0; index < mandFields.length; index++) { 20 | if (g_form.getValue(mandFields[index]).trim() == "") { 21 | g_form.setMandatory(mandFields[index], true); 22 | error = true; 23 | errorFields.push(g_form.getLabelOf(mandFields[index])); 24 | } 25 | } 26 | 27 | if (error && (errorFields.length > 0)) { 28 | g_form.addErrorMessage(getMessage("The following fields are mandatory: ") + ": " + errorFields.join(", ")); 29 | } 30 | return !error; 31 | } 32 | -------------------------------------------------------------------------------- /Client Scripts/getReference/ReadMe.md: -------------------------------------------------------------------------------- 1 | This code runs on client side to fetch any field value from the reference field record. 2 | -------------------------------------------------------------------------------- /Client Scripts/getReference/getReference.js: -------------------------------------------------------------------------------- 1 | /** 2 | * fieldName_current {string}: A REFERENCE type field name on current record 3 | * function {function}: An anonymous function used as a callback function 4 | * recObject {object/GlideRecord object}: GlideRecord object of the record in reference field 5 | * fieldName_ref {string}: A field name on the returned record to perform an action based on it's value 6 | * 7 | */ 8 | 9 | g_form.getReference("fieldName_current", function (recObject) { 10 | if (recObject["fieldName_reference"] == true) { 11 | // do something 12 | } 13 | }); 14 | -------------------------------------------------------------------------------- /Client Scripts/getReference/script.js: -------------------------------------------------------------------------------- 1 | var ans = g_form.getReference('field_name', doAlert); // You can select any 'field name' just make sure the field is reference field && doAlert is a callback function 2 | 3 | function doAlert(ans) { 4 | var res = ans.field_name_2; // field_name_2 is any field on the referenced record. 5 | } 6 | -------------------------------------------------------------------------------- /Date Time/convertEpochToDateTime.js: -------------------------------------------------------------------------------- 1 | convertEpochToDateTime: function(/*Integer*/ epochTime){ 2 | var gdt = new GlideDateTime(); 3 | gdt.setNumericValue(epochTime*1000); 4 | return gdt; 5 | } 6 | -------------------------------------------------------------------------------- /Error Handling/Error Handling.js: -------------------------------------------------------------------------------- 1 | try{ 2 | ) 3 | 4 | catch(err){ 5 | g_form.addErrorMessage("A runtime error occured: " + err); 6 | } 7 | 8 | -------------------------------------------------------------------------------- /Error Handling/README.md: -------------------------------------------------------------------------------- 1 | 2 | ## Error Handling with Syntax Macros 3 | 4 | ### Overview 5 | 6 | This includes a simple error handling example using syntax macros to streamline the process. The following code snippet captures any runtime errors encountered during client script execution and uses `g_form.addErrorMessage` to notify the user, improving the Developers experience by providing clear feedback. 7 | -------------------------------------------------------------------------------- /Flow Designer/DataStreaminScript/code.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | 3 | try { 4 | ​ 5 | // Execute Data Stream Action. 6 | var stream = sn_fd.FlowAPI.executeDataStreamAction('Actionname with Scope in front'); //global.test 7 | ​ 8 | // Process each item in the data stream 9 | while (stream.hasNext()) { 10 | ​ 11 | // Get a single item from the data stream. 12 | var user = stream.next(); 13 | 14 | // Only log the first item in each page 15 | if (stream.getItemInPageIndex() == 0) { 16 | gs.info('first user on page is ' + user.name); 17 | } 18 | } 19 | } catch (ex) { 20 | var message = ex.getMessage(); 21 | gs.error(message); 22 | } finally { 23 | stream.close(); 24 | } 25 | 26 | })(); 27 | -------------------------------------------------------------------------------- /Flow Designer/DataStreaminScript/readme.md: -------------------------------------------------------------------------------- 1 | This macros are used when you call a data stream action from Flow API and then if you want to parse through the records of the output of data stream 2 | -------------------------------------------------------------------------------- /Flow Designer/Extract Data From Excel/code.js: -------------------------------------------------------------------------------- 1 | (function execute(inputs, outputs) { 2 | // This code will look up for the file and get the data from attachment 3 | 4 | var parser = new sn_impex.GlideExcelParser(); 5 | var attachment = new GlideSysAttachment(); 6 | 7 | // use attachment sys id of an excel file 8 | 9 | var attachmentStream = attachment.getContentStream(inputs.cis_from_attachment); 10 | 11 | parser.parse(attachmentStream); 12 | 13 | //retrieve the column headers 14 | var headers = parser.getColumnHeaders(); 15 | var header1 = headers[0]; 16 | var header2 = headers[1]; 17 | 18 | var excel_cis = []; 19 | var instance_ids = []; 20 | 21 | while(parser.next()) 22 | { 23 | var row = parser.getRow(); 24 | excel_cis.push(row[header1]); 25 | instance_ids.push(row[header2]); 26 | } 27 | outputs.ci = excel_cis; 28 | outputs.instance_ids = instance_ids; 29 | 30 | })(inputs, outputs); 31 | -------------------------------------------------------------------------------- /Flow Designer/Extract Data From Excel/readme.md: -------------------------------------------------------------------------------- 1 | This macro will be helpful to extract data from attchment and pass the excel data as input in Flow Designer Action. 2 | 3 | E.g 4 | 5 | 100 CIs are loaded via excel template and you need to extract the data from excel once request is submitted and query the CMDB say BMC via integration to look for all the attribute. 6 | -------------------------------------------------------------------------------- /Flow Designer/GlideflowAPI/code.js: -------------------------------------------------------------------------------- 1 | // Start a Flow 2 | (function() { 3 | var inputs = {}; 4 | inputs['current'] = { // GlideRecord 5 | table : 'table_name', 6 | sys_id : 'sys_id of record' 7 | }; 8 | inputs['table_name'] = 'table_name'; 9 | GlideFlow.startFlow('global.flow_name', inputs) 10 | .then( 11 | function(execution) { 12 | console.log('Started flow_name with execution id :' + execution.getExecutionId()); 13 | }, 14 | function(error) { 15 | console.log('Unable to start flow: ' + error); 16 | } 17 | ); 18 | })(); 19 | -------------------------------------------------------------------------------- /Flow Designer/GlideflowAPI/readme.md: -------------------------------------------------------------------------------- 1 | This GlideFlow API allows you to call a Flow from client side scripts. You need to pass the inputs like table name and Sys id of record for which this flow should be triggered. 2 | -------------------------------------------------------------------------------- /Flow Designer/flowapitocallFlow/code.js: -------------------------------------------------------------------------------- 1 | (function() { 2 | 3 | try { 4 | var inputs = {}; 5 | inputs['table_name'] = 'Table Name'; 6 | inputs['current'] = ; // GlideRecord of table: sc_req_item 7 | 8 | // Start Asynchronously: Uncomment to run in background. 9 | // sn_fd.FlowAPI.getRunner().flow('APPLICATIONSCOPE.FLOW NAME').inBackground().withInputs(inputs).run(); 10 | 11 | // Execute Synchronously: Run in foreground. 12 | sn_fd.FlowAPI.getRunner().flow('APPLICATIONSCOPE.FLOW NAME').inForeground().withInputs(inputs).run(); 13 | 14 | } catch (ex) { 15 | var message = ex.getMessage(); 16 | gs.error(message); 17 | } 18 | 19 | })(); 20 | -------------------------------------------------------------------------------- /Flow Designer/flowapitocallFlow/readme.md: -------------------------------------------------------------------------------- 1 | This script shows how to start flow designer flow from Server side script. It need inputs parameters, Table name and a flow name along with the scope of the flow. 2 | 3 | Please see the code and replace the comments properly to use it. 4 | -------------------------------------------------------------------------------- /General/ArrayFilter.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Description : The .filter() method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument method. 3 | * @orignalArray : Array which needs to be transformed 4 | * @newArray : Array transformed from orignal array using filter 5 | * @return : Transformed Array element 6 | */ 7 | 8 | var newArray = orignalArray.filter(function(val, index){ 9 | // Business logic to be worked on each element 10 | // If evaluate to true then pushed to newArray else ignored 11 | return ; 12 | }) 13 | -------------------------------------------------------------------------------- /General/arraySortEs5.js: -------------------------------------------------------------------------------- 1 | /** 2 | * JS sort function using ES5 syntax 3 | * @param {array} myArray - Array variable which has to be sorted based on a custom logic 4 | * @return {array} - The sorted array 5 | */ 6 | sortArrayUsingEs5: function(myArray) { 7 | 8 | // Need to call the sort function of array object 9 | return myArray.sort(function(itemA, itemB) { 10 | /** 11 | * The sorting logic comes here 12 | * @param {object} itemA - The first element for comparison. Will never be undefined. 13 | * @param {object} itemB - The second element for comparison. Will never be undefined. 14 | * 15 | * @return {number} - Nedd to return three different numbers based on the following logic: 16 | * If itemA is sorted before itemB, then the return value will be -1 (or any other negative number) 17 | * If itemB is sorted before itemA, then the return value will be 1 (or any other positive number) 18 | * If itemA equals with itemB, then the return value will be 0 19 | * 20 | * itemA and itemB can be a complex object as well, the sorting logic can be based on any attributes of the main objects. 21 | */ 22 | 23 | if (/* Logic here which checks that itemA is sorted before itemB */ itemA < itemB) 24 | return -1; 25 | 26 | if (/* Logic here which checks that itemB is sorted before itemA */ itemA > itemB) 27 | return 1; 28 | 29 | // Otherwise 30 | return 0; 31 | }); 32 | }, 33 | -------------------------------------------------------------------------------- /General/arraySortEs6.js: -------------------------------------------------------------------------------- 1 | /** 2 | * JS sort function using ES6+ syntax 3 | * @param {array} myArray - Array variable which has to be sorted based on a custom logic 4 | * @return {array} - The sorted array 5 | */ 6 | sortArrayUsingEs6Plus: function(myArray) { 7 | // Need to call the sort function of array object 8 | return (myArray.sort((itemA, itemB) => { 9 | /** 10 | * The sorting logic comes here 11 | * @param {object} itemA - The first element for comparison. Will never be undefined. 12 | * @param {object} itemB - The second element for comparison. Will never be undefined. 13 | * 14 | * @return {number} - Nedd to return three different numbers based on the following logic: 15 | * If itemA is sorted before itemB, then the return value will be -1 (or any other negative number) 16 | * If itemB is sorted before itemA, then the return value will be 1 (or any other positive number) 17 | * If itemA equals with itemB, then the return value will be 0 18 | * 19 | * itemA and itemB can be a complex object as well, the sorting logic can be based on any attributes of the main objects. 20 | */ 21 | 22 | if (/* Logic here which checks that itemA is sorted before itemB */ itemA < itemB) 23 | return -1; 24 | 25 | if (/* Logic here which checks that itemB is sorted before itemA */ itemA > itemB) 26 | return 1; 27 | 28 | // Otherwise 29 | return 0; 30 | })); 31 | }, 32 | -------------------------------------------------------------------------------- /General/for.js: -------------------------------------------------------------------------------- 1 | for (var i=0; i< myArray.length; i++) { 2 | //myArray[i]; 3 | } -------------------------------------------------------------------------------- /General/foreach.js: -------------------------------------------------------------------------------- 1 | for (property in event) { 2 | //code block 3 | if (condition) { //optional 4 | continue; //skip the rest of the code and go to next property in the event 5 | } 6 | } -------------------------------------------------------------------------------- /General/getprop.js: -------------------------------------------------------------------------------- 1 | gs.getProperty('$0', 'default value'); //enter your property name here, set an Option default parameter 2 | -------------------------------------------------------------------------------- /General/if-else.js: -------------------------------------------------------------------------------- 1 | if (condition1) { 2 | // you rcode here 3 | } else if (condition2) { 4 | // you rcode here 5 | } else { 6 | // you rcode here 7 | } 8 | -------------------------------------------------------------------------------- /General/if.js: -------------------------------------------------------------------------------- 1 | if ("expression") { 2 | // code block 3 | } 4 | -------------------------------------------------------------------------------- /General/map.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Description : The map() method creates a new array with the results of calling a function for every array element. 3 | * @orignalArray : Array which needs to be transformed 4 | * @newArray : Array transformed from orignal array using MAP 5 | * @return : Transformed Array element 6 | */ 7 | 8 | var newArray = orignalArray.map(function(val, index){ 9 | // Business logic to be worked on each element of orignalArray 10 | return ; 11 | }) 12 | -------------------------------------------------------------------------------- /General/switchcase: -------------------------------------------------------------------------------- 1 | switch("expression") { 2 | case x: 3 | // code block 4 | break; 5 | case y: 6 | // code block 7 | break; 8 | default: 9 | // code block 10 | } 11 | -------------------------------------------------------------------------------- /General/trycatch: -------------------------------------------------------------------------------- 1 | try { 2 | //your script 3 | 4 | } catch (ex) { 5 | var message = ex.message; 6 | gs.error("Error in system logs: " + message); 7 | } 8 | -------------------------------------------------------------------------------- /General/while.js: -------------------------------------------------------------------------------- 1 | while ("expression") { 2 | // Code Block 3 | } -------------------------------------------------------------------------------- /GlideAggregate/GlideAggregate.js: -------------------------------------------------------------------------------- 1 | var ga = new GlideAggregate('tableName'); 2 | ga.addAggregate('COUNT', 'field'); 3 | ga.orderBy('field'); 4 | ga.query(); 5 | while(ga.next()) { 6 | 7 | } 8 | -------------------------------------------------------------------------------- /GlideAggregate/GlideAggregateES12: -------------------------------------------------------------------------------- 1 | // Count records in a table that match a specific condition 2 | let ga = new GlideAggregate('table_name'); 3 | ga.addAggregate('COUNT'); 4 | ga.addQuery('field', 'value'); 5 | ga.query(); 6 | 7 | if (ga.next?.()) { 8 | gs.info(ga.getAggregate('COUNT') ?? 0); 9 | } 10 | -------------------------------------------------------------------------------- /GlideAggregate/GlideAggregate_GroupingIncidents_Calculate_AverageTimetoclose.js: -------------------------------------------------------------------------------- 1 | var ga = new GlideAggregate('incident'); 2 | ga.addQuery('state', '!=', 'Closed'); // Filter for open incidents only 3 | ga.groupBy('assigned_to'); 4 | ga.addAggregate('COUNT', 'number'); 5 | ga.addAggregate('AVG', 'time_to_close'); 6 | ga.query(); 7 | 8 | while (ga.next()) { 9 | var assigned_to = ga.get('assigned_to'); 10 | var count = ga.get('result'); 11 | var avgTimeToClose = ga.get('result.avg_time_to_close'); 12 | 13 | gs.info('Assigned to: ' + assigned_to + ', Incident Count: ' + count + ', Average Time to Close: ' + avgTimeToClose); 14 | } 15 | -------------------------------------------------------------------------------- /GlideAggregate/glideAggregateSetAggregateWindow.js: -------------------------------------------------------------------------------- 1 | //Limits the number of rows in a table that the aggregate query can include. 2 | 3 | var ga = new GlideAggregate('incident'); 4 | ga.addAggregate('COUNT', 'category'); 5 | ga.setAggregateWindow(0, 10); 6 | ga.query(); 7 | while (ga.next()) { 8 | var incidentCount = ga.getAggregate('COUNT', 'category'); 9 | gs.info('{0} count: {1}', [ga.getValue('category'), incidentCount]); 10 | } -------------------------------------------------------------------------------- /GlideAggregate/glideaggregateaddtrend.js: -------------------------------------------------------------------------------- 1 | //Adds trends for a field 2 | var trend = new GlideAggregate('incident'); 3 | trend.addTrend ('opened_at','month'); 4 | trend.addAggregate('COUNT'); 5 | trend.setGroup(false); 6 | trend.query(); 7 | while(trend.next()) { 8 | gs.print(trend.getValue('timeref') + ': ' + trend.getAggregate('COUNT')); 9 | } 10 | -------------------------------------------------------------------------------- /GlideAggregate/vargragg.js: -------------------------------------------------------------------------------- 1 | var ga = new GlideAggregate('$0'); //add the required table name 2 | ga.addAggregate('COUNT', 'field');// set the counter on a field 3 | ga.orderBy('field'); //orderby 4 | ga.query(); 5 | while(ga.next()) { 6 | gs.info(ga.getAggregate('COUNT')); //print the count 7 | } 8 | -------------------------------------------------------------------------------- /GlideAjax/Concise way of doing a GlideAJAX call/readme.md: -------------------------------------------------------------------------------- 1 | ## Concise way of doing a GlideAJAX call 2 | 3 | new GlideAjax('ScriptInclude').getXMLAnswer(onAnswer(), { 'sysparm_name': '', 'sysparm_param_1': '', ..., 'sysparm_param_n': '' }); 4 | -------------------------------------------------------------------------------- /GlideAjax/ajax.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: 3 | * @class ScriptInclude Class Name: ScriptIncludeClass 4 | * @function ScriptInclude Function name being called: scriptIncludeFunction 5 | * @param Additional Parameters: sysparm_custom_parameter 6 | * @callback Callback Method that will be called: callbackFunction 7 | */ 8 | 9 | var ga = new GlideAjax('ScriptIncludeClass'); 10 | ga.addParam('sysparm_name', 'scriptIncludeFunction'); 11 | ga.addParam('sysparm_custom_parameter', JSON.stringify({ "foo": "bar" })); 12 | ga.getXML(function (response) { 13 | var responseDocument = response.responseXML.documentElement; 14 | var answer = responseDocument.getAttribute('answer'); 15 | var serverObj = JSON.parse(answer); 16 | console.log(serverObj); 17 | }); 18 | -------------------------------------------------------------------------------- /GlideAjax/ajax_client_answer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Description: 3 | * @class {string} ScriptInclude Class Name: ScriptIncludeClass 4 | * @function {string} ScriptInclude Function name being called: scriptIncludeFunction 5 | * @param {string} Additional Parameters: sysparm_parameter_name 6 | * @callback {function} Callback Method that will be called: callbackFunction 7 | */ 8 | 9 | var ga = new GlideAjax("ScriptIncludeClass"); 10 | ga.addParam("sysparm_name", "scriptIncludeFunction"); 11 | ga.addParam("sysparm_parameter_name", "string_value"); 12 | ga.getXMLAnswer(function (answer) { 13 | if (answer) { 14 | answer = JSON.parse(answer); 15 | // Perform action based on return values 16 | //g_form.setValue("fieldName", answer); 17 | } 18 | }); 19 | -------------------------------------------------------------------------------- /GlideAjax/ajax_server.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Purpose: server side code for GlideAjax function that's defined inside client callable Script Include class 3 | * Description: 4 | * @funciton Function name that's being called in the ajax script: scriptIncludeFunction 5 | * @param Parameters that are passed from client side: sysparm_custom_parameter 6 | * @param the table that's being queried: table 7 | * @param the encoded query string for GlideRecord: query_string 8 | * one can replace the gs.addErrorMessage with gs.log or remove once the development and testing is completed 9 | */ 10 | 11 | scriptIncludeFunction: function () { 12 | try { 13 | var parms = this.getParameter('sysparm_custom_parameter'); 14 | 15 | var parm_obj = JSON.parse(parms); 16 | var result_obj = {}; 17 | var gr = new GlideRecord('table'); 18 | gr.addEncodedQuery('query_string'); 19 | gr.query(); 20 | while (gr.next()) { 21 | 22 | gs.addInfoMessage("Testing: "); 23 | } 24 | 25 | return JSON.stringify(result_obj); 26 | } catch (error) { 27 | gs.addErrorMessage("Error from Server: " + error.getMessage()); 28 | } 29 | }, 30 | -------------------------------------------------------------------------------- /GlideAjax/gajax.js: -------------------------------------------------------------------------------- 1 | var g_ajax = new GlideAjax('scope.ScriptIncludeName'); // pass name of Client callable script include 2 | g_ajax.addParam('sysparm_name','scriptIncludeFunctionName'); // pass function name which will return result 3 | g_ajax.addParam('sysparm_param1','value1'); // optional 4 | g_ajax.addParam('sysparm_param2','value2'); // optional 5 | g_ajax.getXMLAnswer(callbackFunctionName); 6 | 7 | function callbackFunctionName(response){ 8 | var answer = response; 9 | //if you are passing array then use below to parse response 10 | //var answer = JSON.parse(response); 11 | } 12 | -------------------------------------------------------------------------------- /GlideAjax/userDetailsAutopopulate-ScriptInclude: -------------------------------------------------------------------------------- 1 | /* 2 | * Return an object containing user field values 3 | * @input {string} sys ID of the requested user 4 | * @returns {JSON object} 5 | */ 6 | 7 | _getUserInfo: function() { 8 | var userDetails = {}; 9 | var userId = this.getParameter('sysparm_user_id'); // attribute set in client script 10 | var userObj = new GlideRecord('sys_user'); 11 | userObj.addQuery('sys_id', userId); //query 12 | userObj.query(); 13 | if (userObj.next()) { 14 | userDetails.field_1 = userObj.field_1.getDisplayValue(); 15 | userDetails.field_2 = userObj.field_2.sys_id.toString(); 16 | 17 | //e.g. Manager field 18 | userDetails.manager = userObj.manager.sys_id.toString(); 19 | } 20 | return JSON.stringify(details); // return the details in a strigified JSON object. 21 | }, 22 | -------------------------------------------------------------------------------- /GlideAjax/userDetailsPopulation-Client: -------------------------------------------------------------------------------- 1 | /*Call the script include UserDetails to fetch the user details from sys_user table 2 | @ Inputs : Requester 3 | @ Output : User details object - Location, Manager and job Title. 4 | */ 5 | 6 | var getUserDetails = new GlideAjax('UserDetails'); //if scoped, add the scope name in GlideAjax Parameter. e.g. 'sn_hr_core.UserDetails' 7 | getUserDetails.addParam('sysparm_name', 'getUserInfo'); // function call 8 | getUserDetails.addParam('sysparm_user_id', newValue); //passing the parameter 9 | getUserDetails.getXML(requesterInfo); 10 | 11 | function requesterInfo(response) { 12 | var answer = response.responseXML.documentElement.getAttribute("answer"); 13 | var userDetailsObj = JSON.parse(answer); //Object contains nuser details 14 | 15 | //Set Field values from user details object - 16 | g_form.setValue('variable_1', userDetailsObj.user_field_1.toString()); 17 | g_form.setValue('variable_2', userDetailsObj.user_field_2.toString()); 18 | g_form.setValue('variable_3', userDetailsObj.user_field_3.toString()); 19 | } 20 | -------------------------------------------------------------------------------- /GlideDateTime/DaysUntilFutureDate.js: -------------------------------------------------------------------------------- 1 | // Initialize the current date and time 2 | var currentDate = new GlideDateTime(); 3 | 4 | // Set the future date (e.g., '2023-12-31 00:00:00') 5 | var futureDate = new GlideDateTime('2023-12-31 00:00:00'); 6 | 7 | // Calculate the difference in milliseconds 8 | var diff = GlideDateTime.subtract(futureDate, currentDate); 9 | 10 | // Convert the difference to days 11 | var daysUntil = Math.floor(diff.getNumericValue() / (1000 * 60 * 60 * 24)); 12 | 13 | // Log the result 14 | gs.info('Days until future date: ' + daysUntil); 15 | -------------------------------------------------------------------------------- /GlideDateTime/UpdatedWithinList.js: -------------------------------------------------------------------------------- 1 | // Retrieve records updated within the last 30 days using date filtering 2 | let gr = new GlideRecord('incident'); 3 | let date = new GlideDateTime(); 4 | date.subtract(30 * 24 * 60 * 60 * 1000); // 30 days ago 5 | gr.addQuery('sys_updated_on', '>=', date); 6 | gr.query(); 7 | 8 | while (gr.next?.()) { 9 | gs.info('Incident ${gr.number} was updated within the last 30 days.'); 10 | } 11 | -------------------------------------------------------------------------------- /GlideDateTime/getlocaldate.js: -------------------------------------------------------------------------------- 1 | var gdt = new GlideDateTime();//Initiate the date time object for the current date & time 2 | gdt.getLocalDate();//Gets the date stored by the date time object, expressed in the standard format, yyyy-MM-dd, and the current user's time zone 3 | -------------------------------------------------------------------------------- /GlideEncrypter/Decrypter.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @Description : This script is used to Decrypt an Triple DES algorithm Encrypted string into normal string 3 | * @encryptedString : String Encrypted with Triple DES algorithm 4 | * @decrString : Decrypted string 5 | **/ 6 | 7 | var geDecrypt = new GlideEncrypter(); 8 | var encrString = ''; 9 | var decrString = geDecrypt.decrypt(encrString); 10 | gs.print("Decrypted string = " + decrString); 11 | -------------------------------------------------------------------------------- /GlideEncrypter/Encrypter.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @Description : This script is used to Encrypts a clear string using the Triple DES algorithm 3 | @orignal_string : Orignal string / normal text 4 | @encrString : Encrypted String 5 | **/ 6 | 7 | var geEncrypt = new GlideEncrypter(); 8 | var orignalString = ''; 9 | var encrString = geEncrypt.encrypt(orignalString); 10 | gs.info("Encrypted string = " + encrString); 11 | -------------------------------------------------------------------------------- /GlideExcelParser/readExcelFile.js: -------------------------------------------------------------------------------- 1 | //Initialize Excel Parser 2 | var excelParser = new sn_impex.GlideExcelParser(); 3 | 4 | //Initialize Attachment API 5 | var glideAttachment = new GlideSysAttachment(); 6 | var attStream = glideAttachment.getContentStream(""); //Replace with the sys_is of attachment 7 | 8 | excelParser.parse(attStream); 9 | 10 | //Retrieve the column headers 11 | var headers = excelParser.getColumnHeaders(); 12 | 13 | while(excelParser.next()) { 14 | var row = excelParser.getRow(); //JSON object of row 15 | //Read each column using headers, for example row[header[0]] 16 | } 17 | 18 | excelParser.close(); // Close the stream and release the document -------------------------------------------------------------------------------- /GlideFilter/caseSensitiveFilter.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @Description : caseSensitiveFilter : Syntax_macro to apply case sensitive filter on a table. 3 | * @table_name : Name of the table on which filter needs to be applied. 4 | * @encoded_query : Filter condition that we want to apply on records. 5 | **/ 6 | 7 | var gr = new GlideRecord(''); 8 | gr.query(); 9 | var condition = ''; 10 | var glideFilter = new GlideFilter(condition, 'filterCondition'); 11 | while (gr.next()) { 12 | if (glideFilter.match(gr, true)) 13 | gs.info("Result : " + gr.getDisplayValue()); 14 | } 15 | -------------------------------------------------------------------------------- /GlideForm/addDecoration: -------------------------------------------------------------------------------- 1 | /* 2 | Add icon decoration to a field's label 3 | Supported icons - icon-user, icon-user-group, icon-lightbulb, icon-home, icon-mobile, icon-comment, icon-mail, icon-locked, icon-database, icon-book, icon-drawer, icon-folder, icon-catalog, icon-tab, icon-cards, icon-tree-right, icon-tree, icon-book-open, icon-paperclip, icon-edit, icon-trash, icon-image, icon-search, icon-power, icon-cog, icon-star, icon-star-empty, icon-new-ticket, icon-dashboard, icon-cart-full, icon-view, icon-label, icon-filter, icon-calendar, icon-script, icon-add, icon-delete, icon-help, icon-info, icon-check-circle, icon-alert, icon-sort-ascending, icon-console, icon-list, icon-form, and icon-livefeed. 4 | color: any CSS color 5 | 6 | Example: g_form.addDecoration('caller_id', 'icon-star', 'Mark as Favorite', 'color-green'); 7 | */ 8 | g_form.addDecoration('field_name', 'icon-type', 'title for icon', 'color'); 9 | -------------------------------------------------------------------------------- /GlideForm/addOption: -------------------------------------------------------------------------------- 1 | g_form.addOption('String fieldName', 'String choiceValue', 'String choiceLabel'); 2 | -------------------------------------------------------------------------------- /GlideForm/addOptionIndex: -------------------------------------------------------------------------------- 1 | g_form.addOption('String fieldName', 'String choiceValue', 'String choiceLabel', Number choiceIndex) 2 | -------------------------------------------------------------------------------- /GlideForm/clearOptions: -------------------------------------------------------------------------------- 1 | g_form.clearOptions('String fieldName') 2 | -------------------------------------------------------------------------------- /GlideModal/UIPage.js: -------------------------------------------------------------------------------- 1 | //Marco for setting up a modal or dialog window to show a UI Page. 2 | 3 | var dialogClass = window.GlideModal ? GlideModal : GlideDialogWindow; 4 | var gm = new dialogClass("example_ui_page"); 5 | gm.setTitle("example_title"); 6 | gm.setPreference("sysparm_x1", x1); 7 | gm.setPreference("sysparm_x2", x2); 8 | gm.setPreference("sysparm_x3", x3); 9 | gm.setWidth(600); 10 | gm.render(); 11 | -------------------------------------------------------------------------------- /GlideModal/g_model for workspace client script: -------------------------------------------------------------------------------- 1 | g_modal.showFrame({ 2 | url: 'url of the UI page', 3 | title: 'Model Title', 4 | size: 'lg', 5 | height: 500, 6 | width: 600, 7 | callback: function(){ 8 | //callback function 9 | } 10 | }); 11 | -------------------------------------------------------------------------------- /GlideModal/glidemodalWithHTML.js: -------------------------------------------------------------------------------- 1 | /* 2 | Don't need to create an UI Page, if you just wanted to show a message in the modal dialog window. The HTML can be directly passed to renderWithContent function 3 | */ 4 | 5 | var htmlDataToDisplay = ''; 6 | var gm = new GlideModal(); 7 | //Sets the dialog title 8 | gm.setTitle( getMessage('MODAL_WINDOW_TITLE_HERE')); 9 | //Opens the dialog with HTML content supplied as input 10 | gm.renderWithContent(htmlDataToDisplay); 11 | -------------------------------------------------------------------------------- /GlideQuery/glidequeryaggregate.js: -------------------------------------------------------------------------------- 1 | var aggregateQueryObj = new global.GlideQuery('table_name') 2 | .where('field_name', 'field_value') 3 | .groupBy('group_by_field') 4 | .aggregate('aggregate_type', 'aggregate_field_name') 5 | .having('aggregate_type', 'aggregate_field_name', 'operator', number_value) 6 | .select() 7 | .forEach(function(row) { 8 | //gs.info(JSON.stringify(row, null, 2)); 9 | }); 10 | -------------------------------------------------------------------------------- /GlideQuery/glidequerydeletemultiple.js: -------------------------------------------------------------------------------- 1 | var deleteQuery = new global.GlideQuery('table_name') 2 | .where('field_name1', 'field_value1') 3 | .where('field_name2', 'field_value2') 4 | .deleteMultiple(); 5 | -------------------------------------------------------------------------------- /GlideQuery/glidequeryinsert.js: -------------------------------------------------------------------------------- 1 | var queryObj = new global.GlideQuery('table_name') 2 | .insert({ 3 | field_name1: 'field_value1', 4 | field_name2: 'field_value2', 5 | field_name3: 'field_value3', 6 | }, ['additiona_field_1', 'additiona_field_2$DISPLAY']) 7 | .get(); 8 | 9 | //gs.info(JSON.stringify(queryObj, null, 2)); 10 | //gs.info(queryObj.additiona_field_2$DISPLAY); 11 | -------------------------------------------------------------------------------- /GlideQuery/glidequeryreduce.js: -------------------------------------------------------------------------------- 1 | // use the reduce method to convert the stream to an array 2 | // alternative to toArray without needing to know the size of the array 3 | var gqTable = new global.GlideQuery('table_name') 4 | .where('field_1', 'query_value') 5 | .select(['field_1', 'field_1$DISPLAY', 'field_2']) 6 | .reduce(function (arr, e) { arr.push(e); return arr; }, []); 7 | -------------------------------------------------------------------------------- /GlideQuery/glidequeryselect.js: -------------------------------------------------------------------------------- 1 | var selectQueryStream = new global.GlideQuery('table_name') 2 | .where('field_name1', 'field_value1') 3 | .where('field_name2', 'operator', 'field_value2') 4 | .select('field_name1', 'field_name2', 'field_name3$DISPLAY') 5 | .forEach(function(row) { 6 | //gs.info(JSON.stringify(row)); 7 | }); 8 | -------------------------------------------------------------------------------- /GlideQuery/glidequeryselectone.js: -------------------------------------------------------------------------------- 1 | var selectQueryObj = new global.GlideQuery('table_name') 2 | .where('field_name1', 'field_value1') 3 | .selectOne('field_name1', 'field_name2', 'field_name3$DISPLAY') 4 | .ifPresent(function(selectQueryObj) { 5 | //gs.info(JSON.stringify(selectQueryObj)); 6 | }); 7 | -------------------------------------------------------------------------------- /GlideQuery/glidequeryupdate.js: -------------------------------------------------------------------------------- 1 | var updateQueryObj = new global.GlideQuery('table_name') 2 | .where('sys_id', 'xxxxxxxxxxxxxxx') 3 | .update({ 4 | field_name1: 'field_value1', 5 | field_name2: 'field_value2', 6 | }); 7 | -------------------------------------------------------------------------------- /GlideQuery/glidequeryupdatemultiple.js: -------------------------------------------------------------------------------- 1 | var updateMultiple = new global.GlideQuery('table_name') 2 | .where('field_name1', 'field_value1') 3 | .where('field_name2', 'field_value2') 4 | .whereNull('field_name3') 5 | .updateMultiple({ 6 | update_field1: 'update_field_value1', 7 | update_field2: 'update_field_value2', 8 | }); 9 | 10 | //gs.info(JSON.stringify(updateMultiple)); 11 | -------------------------------------------------------------------------------- /GlideQuery/glidequerywithAcls: -------------------------------------------------------------------------------- 1 | var getData = new global.GlideQuery('table_name') 2 | .withAcls() 3 | .limit(numberOfRecords) 4 | .orderByDesc('field_name') 5 | .select('field_name') 6 | .toArray(); 7 | 8 | //Returns a JSON Object, use stringify function to convert into a string. 9 | -------------------------------------------------------------------------------- /GlideRecord/GetRecordsES12: -------------------------------------------------------------------------------- 1 | // Code for fethcing the records via GlideRecord supporting ES12 syntax 2 | let gr = new GlideRecord("$0"); 3 | gr.addQuery("name", "value"); 4 | gr.query(); 5 | 6 | if (gr.next?.()) { 7 | // Do something if the record exists 8 | } 9 | -------------------------------------------------------------------------------- /GlideRecord/GlideFetchChildRecords.js: -------------------------------------------------------------------------------- 1 | // Description : This macro syntax GlideRecord the specific table to retrieve and process child records from that table 2 | // Modify parent_sys_id, 'table_name',parent_reference_field_name according to your requirement 3 | 4 | // code 5 | var parent_sys_id = 'parent_sys_id'; // parent sys_id 6 | var childRecord = new GlideRecord('table_name'); // Glide record the table 7 | childRecord.addQuery('parent_reference_field_name', parent_sys_id); // filter the record according to parent sys_id 8 | childRecord.query(); // query the table 9 | while(childRecord.next()){ 10 | gs.info(" Child Record Number " + childRecord.getValue('number')); // child record number 11 | gs.info(" Child Record Short Description " + childRecord.getValue('short_description')); // child record short description 12 | } 13 | 14 | // Example 15 | var parent_sys_id = 'a623cdb073a023002728660c4cf6a768'; // parent sys_id 16 | var childRecord = new GlideRecord('incident'); // Glide record the incident table 17 | childRecord.addQuery('parent_incident', parent_sys_id); // filter the record according to parent sys_id 18 | childRecord.query(); // query the table 19 | while(childRecord.next()){ 20 | gs.info(" Child Record Number : " + childRecord.getValue('number')); // child incident record number 21 | gs.info(" Child Record Short Description : " + childRecord.getValue('short_description')); // child incident short description 22 | } 23 | -------------------------------------------------------------------------------- /GlideRecord/GlideRecordApplyTemplate.js: -------------------------------------------------------------------------------- 1 | var grRecord = new GlideRecord(); 2 | grRecord.initialize(); 3 | grRecord.applyTemplate(); 4 | grRecord.insert(); 5 | -------------------------------------------------------------------------------- /GlideRecord/GlideRecordUpdateMultiple.js: -------------------------------------------------------------------------------- 1 | var grTable = new GlideRecord('table'); 2 | grTable.addEncodedQuery(" "); 3 | grTable.setValue('field','value'); 4 | grTable.updateMultiple(); 5 | -------------------------------------------------------------------------------- /GlideRecord/InsertRecordES12: -------------------------------------------------------------------------------- 1 | // Insert a new record 2 | let gr = new GlideRecord('table_name'); 3 | gr.initialize(); 4 | gr.field_name = 'value'; 5 | gr.insert?.(); 6 | -------------------------------------------------------------------------------- /GlideRecord/UpdateRelatedRecords: -------------------------------------------------------------------------------- 1 | // Retrieve related records from another table and process them 2 | let parentGR = new GlideRecord('parent_table'); 3 | parentGR.addEncodedQuery('query'); 4 | parentGR.query(); 5 | 6 | while (parentGR.next?.()) { 7 | let taskGR = new GlideRecord('child_table'); 8 | taskGR.addQuery('parent', parentGR.sys_id); 9 | taskGR.query(); 10 | 11 | while (taskGR.next?.()) { 12 | taskGR.state = 'value'; 13 | taskGR.update?.(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /GlideRecord/applyEncodedQuery.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @Description : applyEncodedQuery(String queryString) method - Sets the values of the specified encoded query terms and applies them to the current GlideRecord 3 | * @table_name : Name of the class on which record needs to be created 4 | * @encoded_query : Encoded query to apply to the current GlideRecord. 5 | **/ 6 | 7 | var newgr = new GlideRecord(''); 8 | var queryString = ''; 9 | newgr.initialize(); 10 | newgr.applyEncodedQuery(queryString); 11 | newgr.insert(); 12 | -------------------------------------------------------------------------------- /GlideRecord/brGlideAbortCheck: -------------------------------------------------------------------------------- 1 | /** 2 | * For example, check if a business rule has a setAbortAction(true) set. 3 | * In these cases it may be useful not to execute the following business rules. 4 | * This is ensured by the following script. 5 | * It can be used in business rule scripts. 6 | */ 7 | if(current.isActionAborted()) { 8 | return; 9 | } 10 | -------------------------------------------------------------------------------- /GlideRecord/clonerecord: -------------------------------------------------------------------------------- 1 | var archIns = new GlideRecord('table'); 2 | archIns.initialize(); 3 | archIns.get('record sys id to clone'); 4 | archIns.number = new global.NumberManager('table name').getNextObjNumberPadded(); 5 | archIns.insert(); 6 | -------------------------------------------------------------------------------- /GlideRecord/getRecordShortVersion: -------------------------------------------------------------------------------- 1 | //A shorter method to fetch a record when sys_id is known. 2 | var gr= new GlideRecordUtil().getGR("table_name","sys_id_of_a_record"); 3 | -------------------------------------------------------------------------------- /GlideRecord/gliderecorddeleteget.js: -------------------------------------------------------------------------------- 1 | var recordGr = new GlideRecord("table_name"); 2 | if (recordGr.get("field_name", "field_value")) { 3 | var isDeleted = recordGr.deleteRecord(); 4 | //gs.info(isDeleted); 5 | } 6 | -------------------------------------------------------------------------------- /GlideRecord/gliderecorddeletemultiple.js: -------------------------------------------------------------------------------- 1 | //Find all inactive incidents and delete them all at once 2 | var gr = new GlideRecord('incident'); 3 | gr.addQuery('active', false); 4 | gr.deleteMultiple(); //Deletes all records in the record set 5 | -------------------------------------------------------------------------------- /GlideRecord/gliderecorddeletequery.js: -------------------------------------------------------------------------------- 1 | var recordGr = new GlideRecord("table_name"); 2 | recordGr.addEncodedQuery("encoded_query"); 3 | recordGr.query(); 4 | while (recordGr.next()) { 5 | var isDeleted = recordGr.deleteRecord(); 6 | //gs.info(isDeleted); 7 | } 8 | -------------------------------------------------------------------------------- /GlideRecord/gliderecordencode.js: -------------------------------------------------------------------------------- 1 | var recordGr = new GlideRecord("table_name"); 2 | recordGr.addEncodedQuery("encoded_query"); 3 | recordGr.query(); 4 | while (recordGr.next()) { 5 | //gs.info(recordGr.getUniqueValue()); 6 | } 7 | -------------------------------------------------------------------------------- /GlideRecord/gliderecordforceupdate.js: -------------------------------------------------------------------------------- 1 | //Force an update to all User records without changing field values 2 | var gr = new GlideRecord('sys_user'); 3 | gr.query(); 4 | while (gr.next()) { 5 | gr.setWorkflow(false); //Do not run business rules 6 | gr.autoSysFields(false); //Do not update system fields 7 | gr.setForceUpdate(true); //Force the update 8 | gr.update(); 9 | } 10 | -------------------------------------------------------------------------------- /GlideRecord/gliderecordget.js: -------------------------------------------------------------------------------- 1 | findValue(); 2 | function findValue(){ 3 | var getgr = new GlideRecord('Table_name'); 4 | getgr.get('sys_id'); 5 | gs.info('Message: ' ); 6 | } 7 | -------------------------------------------------------------------------------- /GlideRecord/gliderecordnodomain.js: -------------------------------------------------------------------------------- 1 | var tableGr = new GlideRecord("table_name"); 2 | tableGr.addQuery("field", "value"); 3 | tableGr.queryNoDomain(); 4 | while (tableGr.next()) { 5 | // 6 | } 7 | -------------------------------------------------------------------------------- /GlideRecord/gliderecordorchain.js: -------------------------------------------------------------------------------- 1 | //Find all incidents with a priority of 1 or 2 2 | var gr = new GlideRecord('incident'); 3 | gr.addQuery('priority', 1).addOrCondition('priority', 2); 4 | gr.query(); 5 | -------------------------------------------------------------------------------- /GlideRecord/gliderecordtoiteratethroughallrecords.js: -------------------------------------------------------------------------------- 1 | // iterate through all records in the GlideRecord and set the Priority field value to 4 (low priority) 2 | //Update the record in the database 3 | 4 | while(ObjectName.next()) 5 | { 6 | ObjectName.priority = 4; 7 | ObjectName.update(); //Query through all records and update the priority as 'Low' (p4) 8 | } 9 | -------------------------------------------------------------------------------- /GlideRecord/gliderecordupdateget.js: -------------------------------------------------------------------------------- 1 | var recordGr = new GlideRecord("table_name"); 2 | if (recordGr.get("field_name", "field_value")) { 3 | recordGr.setValue("field_name", "field_value"); 4 | recordGr.setValue("field_name", "field_value"); 5 | recordGr.setValue("field_name", "field_value"); 6 | var id = recordGr.update("update_reason"); 7 | //gs.info(id); 8 | } 9 | -------------------------------------------------------------------------------- /GlideRecord/gliderecordupdatequery.js: -------------------------------------------------------------------------------- 1 | var recordGr = new GlideRecord("table_name"); 2 | recordGr.addEncodedQuery("encoded_query"); 3 | recordGr.query(); 4 | while (recordGr.next()) { 5 | recordGr.setValue("field_name", "field_value"); 6 | recordGr.setValue("field_name", "field_value"); 7 | recordGr.setValue("field_name", "field_value"); 8 | var id = recordGr.update("update_reason"); 9 | //gs.info(id); 10 | } 11 | -------------------------------------------------------------------------------- /GlideRecord/gr-update-or-insert.js: -------------------------------------------------------------------------------- 1 | //Description: This macro checks if a record exists based on a specific query. 2 | // If it does, it updates the designated field; if not, it creates a new record. 3 | // Modify table_name, field_name, field_to_update and the associated values as needed. 4 | 5 | 6 | //Code 7 | var gr = new GlideRecord('table_name'); 8 | gr.addQuery('field_name', 'value'); 9 | gr.query(); 10 | 11 | if (gr.next()) { 12 | // Update existing record 13 | gr.field_to_update = 'new_value'; 14 | gr.update(); 15 | gs.info('Updated record: ' + gr.sys_id); 16 | } else { 17 | // Insert new record 18 | gr.initialize(); 19 | gr.field_name = 'value'; 20 | var newRecordID = gr.insert(); 21 | gs.info('Inserted new record: ' + newRecordID); 22 | } 23 | 24 | 25 | 26 | //Example 27 | var gr = new GlideRecord('incident'); 28 | gr.addQuery('short_description', 'Test GR'); 29 | gr.query(); 30 | 31 | if (gr.next()) { 32 | // Update existing record 33 | gr.description = 'Updated Successfully'; 34 | gr.update(); 35 | gs.info('Updated record: ' + gr.sys_id); 36 | } else { 37 | // Insert new record 38 | gr.initialize(); 39 | gr.short_description = 'Test GR'; 40 | gr.description = 'Inserted Successfully'; 41 | var newRecordID = gr.insert(); 42 | gs.info('Inserted new record: ' + newRecordID); 43 | } 44 | -------------------------------------------------------------------------------- /GlideRecord/groder.js: -------------------------------------------------------------------------------- 1 | //Find all active incidents and order the results ascending by category then descending by created date 2 | var gr = new GlideRecord('incident'); 3 | gr.addQuery('active', true); 4 | gr.orderBy('category'); 5 | gr.orderByDesc('sys_created_on'); 6 | gr.query(); 7 | -------------------------------------------------------------------------------- /GlideRecord/incidentbypriority.js: -------------------------------------------------------------------------------- 1 | //Example of Add or condtion 2 | var gr = new GlideRecord('incident'); 3 | gr.addQuery('priority','4').addOrCondition('priority', '3'); //getting the priority 3 or priority 4 incidents 4 | gr.query(); 5 | while(gr.next()){ 6 |     gs.print(gr.number); 7 |   8 | } 9 | gs.print(gr.getRowCount()) 10 | -------------------------------------------------------------------------------- /GlideRecord/interatethroughonlyfirstrecord.js: -------------------------------------------------------------------------------- 1 | // Set the Priority field value to 4 (Low priority) for the first record in the GlideRecord 2 | 3 | // Updat ethe record in the Database 4 | 5 | if(xyz.next()) 6 | { 7 | xyz.priority = 4; // 'yxz' is object name 8 | xyz.update(); 9 | } 10 | -------------------------------------------------------------------------------- /GlideRecord/newgr.js: -------------------------------------------------------------------------------- 1 | // A common pattern for instantiating a new record with default values and a sys_id 2 | var newgr = new GlideRecord('table_name'); 3 | newgr.newRecord(); 4 | newgr.setValue('field','value'); 5 | newgr.insert(); 6 | -------------------------------------------------------------------------------- /GlideRecord/noauto.js: -------------------------------------------------------------------------------- 1 | gr.autoSysFields(false); // Do not update sys_updated_by, sys_updated_on, sys_mod_count, sys_created_by, and sys_created_on 2 | gr.setWorkflow(false); // Do not run any other business rules 3 | -------------------------------------------------------------------------------- /GlideRecordSecure/CreateOrUpdate.js: -------------------------------------------------------------------------------- 1 | // Description: This macro verifies the presence of a record in a specified table using a defined query. 2 | // If the record exists, it updates a designated field with a new value. If the record does not exist, 3 | // it initializes a new record and inserts it into the table. 4 | // Users should customize 'table_name', 'field_name', 'field_to_update', and the relevant values as necessary. 5 | 6 | // Code 7 | var tableGR = new GlideRecordSecure('table_name'); // Instantiate a GlideRecordSecure object for the specified table 8 | tableGR.addQuery('field_name', 'value'); // Add a query to locate existing records 9 | tableGR.query(); // Execute the query 10 | 11 | if (tableGR.next()) { 12 | // Update the found record 13 | tableGR.field_to_update = 'new_value'; // Set the new value for the specified field 14 | tableGR.update(); // Commit the changes to the existing record 15 | //gs.info('Updated record: ' + tableGR.sys_id); // Log the sys_id of the updated record 16 | } else { 17 | // Insert a new record 18 | tableGR.initialize(); // Prepare the GlideRecord for creating a new entry 19 | tableGR.field_name = 'value'; // Assign the value for the new record's field 20 | var newRecordID = tableGR.insert(); // Insert the new record into the database 21 | //gs.info('Inserted new record: ' + newRecordID); // Log the ID of the newly created record 22 | } 23 | -------------------------------------------------------------------------------- /GlideRecordSecure/CreateRecord.js: -------------------------------------------------------------------------------- 1 | // A common pattern for instantiating a new record with default values and a sys_id 2 | var newgr = new GlideRecordSecure('table_name'); 3 | //uncomment accordingly either of initialize vs newRecord line as per requirement 4 | //newgr.initialize(); //Creates an empty record suitable for population before an insert. 5 | newgr.newRecord(); //Creates a GlideRecord, set the default values for the fields and assign a unique id to the record. 6 | newgr.setValue('field','value'); 7 | newgr.insert(); 8 | -------------------------------------------------------------------------------- /GlideRecordSecure/deleteMultiple.js: -------------------------------------------------------------------------------- 1 | // Fetch all records that meet the specified criteria and delete them in bulk 2 | var tableGR = new GlideRecordSecure('table_name'); // Instantiate a GlideRecordSecure object for the designated table 3 | tableGR.addQuery('field', value); // Add a query to filter records according to a specific condition 4 | tableGR.deleteMultiple(); // Deletes all records that correspond to the query in the record set 5 | -------------------------------------------------------------------------------- /GlideRecordSecure/getRecord.js: -------------------------------------------------------------------------------- 1 | // Retrieve a specific record from a specified table using its sys_id 2 | var tableGR = new GlideRecordSecure('Table_name'); // Create a GlideRecordSecure object for the specified table 3 | if (tableGR.get('sys_id')) { // Attempt to retrieve the record with the specified sys_id 4 | // Code/logic for processing the found record goes here 5 | 6 | } else { 7 | gs.info('Message: No record found!'); // Log a message if no record is found 8 | } 9 | -------------------------------------------------------------------------------- /GlideRecordSecure/updateMultipleTemplate.js: -------------------------------------------------------------------------------- 1 | // Update multiple records in a specified table based on a defined query 2 | var grTable = new GlideRecordSecure('table'); // Create a GlideRecordSecure object for the specified table 3 | grTable.addEncodedQuery(" "); // Add an encoded query to filter records (replace with actual query) 4 | grTable.setValue('field', 'value'); // Set the value for the specified field to be updated 5 | grTable.updateMultiple(); // Update all records that match the query with the new field value 6 | -------------------------------------------------------------------------------- /GlideRecordSecure/updateRecordQuery.js: -------------------------------------------------------------------------------- 1 | // Create a new GlideRecordSecure object for the specified table 2 | var recordGr = new GlideRecordSecure("table_name"); 3 | 4 | // Add an encoded query to filter records based on specified criteria 5 | recordGr.addEncodedQuery("encoded_query"); 6 | 7 | // Execute the query to retrieve matching records 8 | recordGr.query(); 9 | 10 | // Loop through each record returned by the query 11 | while (recordGr.next()) { 12 | // Set the value for the first field to a specified value 13 | recordGr.setValue("field_name", "field_value"); 14 | 15 | // Set the value for a second field to a specified value 16 | //recordGr.setValue("field_name", "field_value"); 17 | 18 | // Set the value for a third field to a specified value 19 | r//ecordGr.setValue("field_name", "field_value"); 20 | 21 | // Update the record with a reason for the update and store the record ID 22 | var id = recordGr.update("update_reason"); 23 | 24 | // Optionally log the updated record ID for debugging purposes 25 | // gs.info(id); 26 | } 27 | -------------------------------------------------------------------------------- /GlideScopedEvaluator/glideEvaluator.js: -------------------------------------------------------------------------------- 1 | var evaluator = new GlideScopedEvaluator(); 2 | evaluator.putVariable('var1', 'value1'); 3 | evaluator.putVariable('var2', 'value2'); 4 | evaluator.evaluateScript(grObj, 'script_field', null); 5 | var result= evaluator.getVariable('result'); 6 | -------------------------------------------------------------------------------- /GlideScopedEvaluator/readme.md: -------------------------------------------------------------------------------- 1 | The GlideScopedEvaluator API allows you to evaluate scripts in a GlideRecord field from both scoped and global server scripts. 2 | The GlideScopedEvaluator API evaluates records with script fields defined. The scope of the script is defined by the scope of the record. 3 | This macro can can be used to with keyword 'GlideEvaluator' follwed by TAB, it will generate GlideScopedEvaluator syntax. 4 | -------------------------------------------------------------------------------- /GlideSecureRandomUtil/GlideSecureRandomUtil.js: -------------------------------------------------------------------------------- 1 | //Methods for generating texts, long values, and integers are offered through the scoped GlideSecureRandomUtil API. 2 | 3 | //getSecureRandomInt() -Generates a pseudo-random integer. 4 | gs.info(GlideSecureRandomUtil.getSecureRandomInt()); 5 | 6 | //getSecureRandomIntBound(Number bound) Generates a pseudo-random integer between 0 (inclusive) and the bound (exclusive) value that you pass into the method. 7 | gs.info(GlideSecureRandomUtil.getSecureRandomIntBound(100)); 8 | 9 | //getSecureRandomLong() Generates pseudo-random long value. 10 | gs.info(GlideSecureRandomUtil.getSecureRandomLong()); 11 | 12 | //getSecureRandomString(Number length) Generates a random alpha-numeric String with the specified length. 13 | gs.info(GlideSecureRandomUtil.getSecureRandomString(20)); -------------------------------------------------------------------------------- /GlideSysAttachment/addAttachment.js: -------------------------------------------------------------------------------- 1 | var attachment = new GlideSysAttachment(); 2 | //The syntax for write api is - , , , 3 | var attachmentSysId = attachment.write(current, 'file_name.txt', 'text/plain', 'file contents'); 4 | gs.info("Attachment Sys ID: " + attachmentSysId); 5 | -------------------------------------------------------------------------------- /GlideSysAttachment/getAttachments.js: -------------------------------------------------------------------------------- 1 | var glideAttachment = new GlideSysAttachment(); 2 | //Get attachments as GlideRecord Objects 3 | var gAttRec = glideAttachment.getAttachments('', ''); //Replace with your table and with sys_id of the record 4 | while(gAttRec.next()){ 5 | //Process each attachment record 6 | } 7 | -------------------------------------------------------------------------------- /GlideSystem/To find Specific String using Index of.js: -------------------------------------------------------------------------------- 1 | //To find any string in the field 2 | var value = current.variables.variablename.getDisplayValue(); 3 | if(value.indexOf('string') > -1){ 4 | //to find a particular string example: Production 5 | current.fieldname = value; 6 | //if the value is found then set the value 7 | } 8 | -------------------------------------------------------------------------------- /GlideSystem/addErrorMessage.js: -------------------------------------------------------------------------------- 1 | //Adds an error message for the current session. 2 | //addErrorMessage(Enter your message) 3 | gs.addErrorMessage("Enter your error text here: " + rules); 4 | -------------------------------------------------------------------------------- /GlideSystem/addInfoMessage.js: -------------------------------------------------------------------------------- 1 | //Use this to have Info Message with the link & number of the original record(for example requested item) while creating a new record on any table(incident), This can be added any UI action or similar. 2 | 3 | gs.addInfoMessage(gs.getMessage("You will be navigated back to {1} upon submission", [current.getLink(), current.number + ""])); 4 | -------------------------------------------------------------------------------- /GlideSystem/dateDiffGlobal: -------------------------------------------------------------------------------- 1 | var gdt1 = GlideDateTime('YYYY-MM-DD hh:mm:ss'); 2 | 3 | var gdt2 = GlideDateTime('YYYY-MM-DD hh:mm:ss'); 4 | 5 | var duration = gs.dateDiff(gdt1.getDisplayValue(), gdt2.getDisplayValue(), false); 6 | 7 | //If true, the value will be returned in number of seconds; if false the value will be returned in ddd hh:mm:ss format. 8 | -------------------------------------------------------------------------------- /GlideSystem/impersonate.js: -------------------------------------------------------------------------------- 1 | try { 2 | // Impersonate to a specific user based on User ID (user_name) 3 | gs.getSession().onlineImpersonate("user_name"); 4 | // TODO - Write the logic here 5 | } 6 | finally { 7 | // In order to avoid unexpected error the unimpersonate action is added to the finally part of code 8 | // which will certainly be executed 9 | gs.getSession().onlineUnimpersonate(); 10 | } 11 | -------------------------------------------------------------------------------- /GlideUser/GlideUser.js: -------------------------------------------------------------------------------- 1 | //Check if a given userName & Password combination is Valid in ServiceNow using Background Script. 2 | 3 | var userName = “name”; // or gs.getUserName() 4 | var password = "password_for_the_user"; 5 | var authed = GlideUser.authenticate(userName, password); 6 | gs.print(authed); //returns true or false. 7 | -------------------------------------------------------------------------------- /GlideUtils/GlideUtils Syntax Macros/GlideUtils.arrayCopy().js: -------------------------------------------------------------------------------- 1 | var originalArray = [1, 2, 3]; 2 | var copiedArray = GlideUtils.arrayCopy(originalArray); 3 | gs.info('Copied Array: ' + copiedArray.join(', ')); 4 | -------------------------------------------------------------------------------- /GlideUtils/GlideUtils Syntax Macros/GlideUtils.arrayFind().js: -------------------------------------------------------------------------------- 1 | var arr = ['apple', 'banana', 'orange']; 2 | var index = GlideUtils.arrayFind(arr, 'banana'); 3 | gs.info('Index of Banana: ' + index); // Output: 1 4 | -------------------------------------------------------------------------------- /GlideUtils/GlideUtils Syntax Macros/GlideUtils.escapeHTML().js: -------------------------------------------------------------------------------- 1 | var unsafeString = ''; 2 | var safeString = GlideUtils.escapeHTML(unsafeString); 3 | gs.info('Escaped HTML: ' + safeString); // Output: <script>alert("Hello");</script> 4 | 5 | -------------------------------------------------------------------------------- /GlideUtils/GlideUtils Syntax Macros/GlideUtils.getCallerStack().js: -------------------------------------------------------------------------------- 1 | var stackTrace = GlideUtils.getCallerStack(); 2 | gs.info('Caller Stack: ' + stackTrace); 3 | -------------------------------------------------------------------------------- /GlideUtils/GlideUtils Syntax Macros/GlideUtils.getClassName().js: -------------------------------------------------------------------------------- 1 | var obj = new GlideRecord('incident'); 2 | var className = GlideUtils.getClassName(obj); 3 | gs.info('Class Name: ' + className); // Output: 'GlideRecord' 4 | -------------------------------------------------------------------------------- /GlideUtils/GlideUtils Syntax Macros/GlideUtils.getKeys().js: -------------------------------------------------------------------------------- 1 | var obj = { name: 'John', age: 30 }; 2 | var keys = GlideUtils.getKeys(obj); 3 | gs.info('Keys: ' + keys.join(', ')); // Output: name, age 4 | -------------------------------------------------------------------------------- /GlideUtils/GlideUtils Syntax Macros/GlideUtils.isNil().js: -------------------------------------------------------------------------------- 1 | var value = null; 2 | var isNil = GlideUtils.isNil(value); 3 | gs.info('Is Nil: ' + isNil); // true if the value is null or undefined 4 | -------------------------------------------------------------------------------- /GlideUtils/GlideUtils Syntax Macros/GlideUtils.isNumeric().js: -------------------------------------------------------------------------------- 1 | var value = '123'; 2 | var isNumber = GlideUtils.isNumeric(value); 3 | gs.info('Is Numeric: ' + isNumber); // true if numeric, false otherwise 4 | 5 | -------------------------------------------------------------------------------- /GlideUtils/GlideUtils Syntax Macros/GlideUtils.parseInt().js: -------------------------------------------------------------------------------- 1 | var str = '123'; 2 | var intValue = GlideUtils.parseInt(str); 3 | gs.info('Parsed Integer: ' + intValue); // Output: 123 4 | -------------------------------------------------------------------------------- /GlideUtils/GlideUtils Syntax Macros/GlideUtils.xmlEscape().js: -------------------------------------------------------------------------------- 1 | var xmlString = 'John & Jane'; 2 | var escapedXML = GlideUtils.xmlEscape(xmlString); 3 | gs.info('Escaped XML: ' + escapedXML); // Output: <name>John & Jane</name> 4 | -------------------------------------------------------------------------------- /GlideUtils/GlideUtils Syntax Macros/README.md: -------------------------------------------------------------------------------- 1 | GlideUtils API is a collection of utility methods that can help you work with different data types and operations. These methods are typically used to simplify common tasks like data conversion, array operations, string manipulation, etc. 2 | **1. GlideUtils.isNumeric():** 3 | • Purpose: Check if a value is numeric. 4 | 5 | **2. GlideUtils.isNil():** 6 | • Purpose: Check if a value is null or undefined. 7 | 8 | **3. GlideUtils.getCallerStack():** 9 | • Purpose: Get the current caller stack trace, useful for debugging. 10 | 11 | **4. GlideUtils.arrayCopy():** 12 | • Purpose: Create a shallow copy of an array. 13 | 14 | **5. GlideUtils.getKeys():** 15 | • Purpose: Get the keys of an object as an array. 16 | 17 | **6. GlideUtils.getClassName():** 18 | • Purpose: Get the name of the class of an object. 19 | 20 | **7. GlideUtils.parseInt():** 21 | • Purpose: Parse a string to an integer. 22 | 23 | **8. GlideUtils.arrayFind():** 24 | • Purpose: Find the index of an element in an array. 25 | 26 | **9. GlideUtils.escapeHTML():** 27 | • Purpose: Escape HTML entities in a string. 28 | 29 | **10. GlideUtils.xmlEscape():** 30 | • Purpose: Escape characters for XML. 31 | -------------------------------------------------------------------------------- /GlideUtils/getRefRecord.js: -------------------------------------------------------------------------------- 1 | $0var caller = current.assigned_to.getRefRecord(); //Returns the GlideRecord for the value populated in the 'assigned_to' field 2 | -------------------------------------------------------------------------------- /HTML/htmlTable.js: -------------------------------------------------------------------------------- 1 | var htmlTable = ''; 2 | htmlTable = htmlTable+''; 3 | htmlTable = htmlTable+''; 4 | htmlTable = htmlTable+''; 5 | htmlTable = htmlTable+''; 6 | htmlTable = htmlTable+''; 7 | htmlTable = htmlTable+''; 8 | htmlTable = htmlTable+''; 9 | htmlTable = htmlTable+''; 10 | htmlTable = htmlTable+'
Header VALUE HERE
Cell VALUE HERE
'; 11 | -------------------------------------------------------------------------------- /HTML/readme.md: -------------------------------------------------------------------------------- 1 | Use this macro to insert scripted HTML table. 2 | 3 | This can be called in Client side as well as server side scripts to get HTML table template if there is need of HTML script to generate table. 4 | 5 | Eg. Insert table in Email Notification script, Display contents in HTML field, generate PDF using HTML template etc 6 | -------------------------------------------------------------------------------- /InboundEmailActions/Inbound Actions: -------------------------------------------------------------------------------- 1 | /* 2 | current.comments = email.body_text; 3 | 4 | if (email.body.short_description != undefined) 5 | current.short_description = email.body.short_description; 6 | 7 | if (email.body_text.assign != undefined) 8 | current.assigned_to = email.body_text.assign; 9 | 10 | if (email.body_text.priority != undefined) 11 | current.priority = email.body_text.priority; 12 | 13 | if (email.body_text.category != undefined) 14 | current.category = email.body_text.category; 15 | 16 | current.insert(); 17 | 18 | */ 19 | -------------------------------------------------------------------------------- /Integration/restmessagesync.js: -------------------------------------------------------------------------------- 1 | try { 2 | var r = new sn_ws.RESTMessageV2('message_name', 'method_name'); 3 | 4 | //override authentication profile 5 | //authentication type ='basic'/ 'oauth2' 6 | //r.setAuthenticationProfile(authentication type, profile name); 7 | 8 | //set a MID server name if one wants to run the message on MID 9 | //r.setMIDServer('MY_MID_SERVER'); 10 | 11 | r.setStringParameter("variable_name1", "variable_value1"); 12 | r.setStringParameter("variable_name2", "variable_value2"); 13 | r.setStringParameter("variable_name3", "variable_value3"); 14 | r.setStringParameterNoEscape("variable_name4", "variable_value4"); 15 | 16 | var response = r.execute(); 17 | var responseBody = response.getBody(); 18 | var httpStatus = response.getStatusCode(); 19 | } 20 | catch(ex) { 21 | var message = ex.message; 22 | //gs.warn('Full Stack Details:'+JSON.stringify(ex,null,4)); 23 | 24 | //Optional: Throw full stack trace 25 | //throw ex 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Integration/soapmessagesync.js: -------------------------------------------------------------------------------- 1 | try { 2 | var r = new sn_ws.SOAPMessageV2('message_name', 'method_name'); 3 | 4 | //override authentication profile 5 | //authentication type ='basic'/ 'oauth2' 6 | //r.setAuthenticationProfile(authentication type, profile name); 7 | 8 | //set a MID server name if one wants to run the message on MID 9 | //r.setMIDServer('MY_MID_SERVER'); 10 | 11 | r.setStringParameter("variable_name1", "variable_value1"); 12 | r.setStringParameter("variable_name2", "variable_value2"); 13 | r.setStringParameter("variable_name3", "variable_value3"); 14 | r.setStringParameterNoEscape("variable_name4", "variable_value4"); 15 | 16 | var response = r.execute(); 17 | var responseBody = response.getBody(); 18 | var httpStatus = response.getStatusCode(); 19 | } 20 | catch(ex) { 21 | var message = ex.message; 22 | } 23 | -------------------------------------------------------------------------------- /JSON/JSONAdv: -------------------------------------------------------------------------------- 1 | var obj = {"key1":"Value1","key2":"Value2"} // Sample JSON which can be replaced with any other JSON Object 2 | 3 | var out = new JSON().getKeys(obj); // Output is an array of 'JSON Object' obj keys 4 | 5 | 6 | -------------------------------------------------------------------------------- /JSON/JSONSyn: -------------------------------------------------------------------------------- 1 | //This Syntax would help to populate with JSON structure with sample key and values to quickly start 2 | 3 | var json_syn = { 4 | "key1":"value1", 5 | "key2":"value2" 6 | } 7 | 8 | -------------------------------------------------------------------------------- /JSON/JSON_Iterator.js: -------------------------------------------------------------------------------- 1 | /** 2 | * This function iterates over each property in a JSON object and logs the key and value. 3 | * 4 | * @example 5 | * // Output: 6 | * // key1: value1 7 | * // key2: value2 8 | * // key3: value3 9 | */ 10 | var jsonObject = { 11 | "key1": "value1", 12 | "key2": "value2", 13 | "key3": "value3" 14 | }; 15 | 16 | /** 17 | * Iterates over each property of the jsonObject. 18 | * Checks if the property is a direct property of the jsonObject, 19 | * then logs the key and corresponding value to the console. 20 | */ 21 | for (var key in jsonObject) { 22 | if (jsonObject.hasOwnProperty(key)) { 23 | console.log(key + ": " + jsonObject[key]); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /JSON/JSON_Response_Builder.js: -------------------------------------------------------------------------------- 1 | /* 2 | # buildJsonResponse Utility Function 3 | 4 | # This function constructs a standardized JSON response for any operation. 5 | It takes three parameters: 6 | - `success` (Boolean): Indicates if the operation was successful (true/false). 7 | - `message` (String): A message providing context or information about the operation's outcome. 8 | - `data` (Object): An object containing any additional data related to the operation (key-value pairs or complex objects). 9 | */ 10 | 11 | 12 | //Function 13 | function buildJsonResponse(success, message, data) { 14 | return JSON.stringify({ 15 | success: success, 16 | message: message, 17 | data: data 18 | }); 19 | } 20 | 21 | // Usage example 22 | var json_data = { 23 | "key1":"value1", 24 | "key2":"value2" 25 | }; 26 | 27 | var response = buildJsonResponse(true, 'Operation successful', json_data); 28 | gs.info('Response: ' + response); 29 | -------------------------------------------------------------------------------- /Label Styles/FieldBold.js: -------------------------------------------------------------------------------- 1 | //Client Script to bold a field label. 2 | //Replace table.field with your desired table and field name 3 | function onLoad(){ 4 | var l = g_form.getLabel('table.field'); 5 | l.style.fontWeight = 'bold'; 6 | } -------------------------------------------------------------------------------- /Label Styles/FieldFlash.js: -------------------------------------------------------------------------------- 1 | /* Client Script for flashing field name 2 | Replace table.field with the table name and field name you want to have flash 3 | Replace color with RGB color or acceptable CSS color like "blue" or "tomato" 4 | Integer that determines how long the label flashes: 5 | 2 for a 1-second flash 6 | 0 for a 2-second flash 7 | -2 for a 3-second flash 8 | -4 for a 4-second flash 9 | */ 10 | function onLoad(){ 11 | g_form.flash("table.field","color",0); 12 | } -------------------------------------------------------------------------------- /MailScript/Add User to CC_BCC.js: -------------------------------------------------------------------------------- 1 | // Add User to CC add a code syntax macro mailcc with following code and use in mailscript 2 | email.addAddress("cc",,); 3 | email.addAddress("bcc",,); 4 | -------------------------------------------------------------------------------- /MailScript/Portal Link/readme.md: -------------------------------------------------------------------------------- 1 | Use this to insert Link to your record in Service Portal. 2 | -------------------------------------------------------------------------------- /MailScript/Portal Link/spLink.js: -------------------------------------------------------------------------------- 1 | //Print current record link that take user to Service Portal. 2 | var url = ''+current.number+''; //Replace sp with your portal. 3 | template.print(url); 4 | -------------------------------------------------------------------------------- /MailScript/getLatestComment.js: -------------------------------------------------------------------------------- 1 | (function runMailScript( /* GlideRecord */ current, /* TemplatePrinter */ template, 2 | /* Optional EmailOutbound */ 3 | email, /* Optional GlideRecord */ email_action, 4 | /* Optional GlideRecord */ 5 | event) { 6 | 7 | //Fetch latest comment and notify 8 | 9 | var comments = current.comments.getJournalEntry(1); 10 | template.print(comments); 11 | 12 | })(current, template, email, email_action, event); 13 | -------------------------------------------------------------------------------- /OutboundEmail Action/sendOutboundEmail.js: -------------------------------------------------------------------------------- 1 | var mail = new GlideEmailOutbound(); 2 | mail.setReplyTo('testing@example.com'); 3 | mail.setFrom('developer@example.com'); 4 | mail.setSubject('ServiceNow Testing'); //setting the subject 5 | mail.addAddress('cc', 'admin@example.com','John Snow'); //specify the address and name 6 | mail.setBody('Hello world!');//sets the email body contents 7 | //mail.addRecipient('hacktoberfest@example.com');//Undocumented in ServiceNow docs but works in global scope. 8 | mail.save();//Triggeres the outbound notification 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Heading](https://github.com/ServiceNowDevProgram/syntax_macros/assets/11089802/93175471-cae9-4e9d-9d7e-56086c19ed6f) 2 | 3 | 4 | # Syntax Macros 5 | 6 | For community contributed [syntax macros](https://docs.servicenow.com/bundle/vancouver-application-development/page/script/general-scripting/concept/c_SyntaxEditor.html) 7 | 8 | 🔔🔔🔔
9 | ***CONTRIBUTORS must follow all guidelines in [CONTRIBUTING.md](CONTRIBUTING.md)*** or run the risk of having your Pull Requests labeled as spam.
10 | 🔔🔔🔔 11 | 12 | ## 13 | 14 | Syntax Macros are little snippets of code stored in ServiceNow that can quickly be used in script fields using shortcuts. By typing the name of the syntax macro and then hitting TAB you can insert the code snippet directly into the field. No more trying to remember how to format GlideAggregate or mistyping the word query. 15 | 16 | [Syntax editor macros... a tiny thing that makes the developer life a lot easier](https://community.servicenow.com/community?id=community_blog&sys_id=3abdeaa9dbd0dbc01dcaf3231f9619d0) 17 | 18 | ## Using Syntax Macros in the Widget Editor 19 | This funtionality is not avaliable out of the box but *can* (and should) be added! [Service Portal: Syntax EditorMacros](https://community.servicenow.com/community?id=community_article&sys_id=4ddc6665dbd0dbc01dcaf3231f96196f) 20 | -------------------------------------------------------------------------------- /RESTMessageV2/restMessageV2.JS: -------------------------------------------------------------------------------- 1 | //Macro to quickly set up a REST call 2 | 3 | 4 | var rest = new sn_ws.RESTMessageV2(); 5 | rest.setEndpoint("end_point"); 6 | rest.setHttpMethod("POST"); //POST, GET, etc. 7 | rest.setRequestHeader("Content-Type", "application/json"); 8 | rest.setLogLevel("all"); 9 | rest.setRequestBody('object with request parameters'); 10 | 11 | var response = rest.execute(); 12 | var responseBody = response.getBody(); 13 | var httpStatus = response.getStatusCode(); 14 | -------------------------------------------------------------------------------- /RestMessage/rest_out.js: -------------------------------------------------------------------------------- 1 | var requestBody; 2 | var responseBody; 3 | var status; 4 | try { 5 | var ws = new sn_ws.RESTMessageV2("", ""); 6 | 7 | // sm.setAuthenticationProfile('oauth2', '1234adsf123212131123qasdsf'); 8 | 9 | ws.setStringParameter("", ""); 10 | ws.setStringParameterNoEscape("", "test"); 11 | 12 | //In milliseconds. Wait at most 10 seconds for response from http request. 13 | ws.setHttpTimeout(10000); 14 | //Might throw exception if http connection timed out or some issue with sending request itself because of encryption/decryption of password. 15 | response = ws.execute(); 16 | responseBody = response.haveError() ? response.getErrorMessage() : response.getBody(); 17 | 18 | status = response.getStatusCode().toString(); 19 | if (status == '200' || status == '201') { 20 | var answer = JSON.parse(responseBody); 21 | } 22 | } catch (ex) { 23 | responseBody = ex.getMessage(); 24 | status = '500'; 25 | //gs.warn('Error processing outbound REST: '+responseBody); 26 | 27 | } finally { 28 | requestBody = ws ? ws.getRequestBody() : null; 29 | } 30 | gs.log(responseBody, ""); 31 | -------------------------------------------------------------------------------- /Scheduled Jobs/User Deactivation Macro/ReadMe.md: -------------------------------------------------------------------------------- 1 | User Deactivation Macro 2 | 3 | Shortcut: deactivateusers 4 | 5 | This macro automatically deactivate users who haven’t logged in for a specified number of days. 6 | -------------------------------------------------------------------------------- /Scheduled Jobs/User Deactivation Macro/User Deactivate Job.js: -------------------------------------------------------------------------------- 1 | var userGR = new GlideRecord('sys_user'); 2 | userGR.addQuery('last_login_time', '<', gs.daysAgoStart(90)); // Change to desired days 3 | userGR.addQuery('active', true); 4 | userGR.query(); 5 | 6 | while (userGR.next()) { 7 | userGR.active = false; 8 | userGR.update(); 9 | } 10 | -------------------------------------------------------------------------------- /Script Include/To Inherit a Script Include/inheritScriptInclude.js: -------------------------------------------------------------------------------- 1 | var ChildScriptInclude = Class.create(); 2 | ChildScriptInclude.prototype = Object.extendsObject(ParentScriptInclude, { 3 | initialize: function() { 4 | // Constructor logic for the child script include 5 | }, 6 | 7 | childFunction: function() { 8 | // Child function logic 9 | }, 10 | 11 | // Override or add more functions as needed 12 | }); 13 | -------------------------------------------------------------------------------- /Script Version Differ/ScriptVersionDiff.js: -------------------------------------------------------------------------------- 1 | (function () { 2 | var oldScript = g_scratchpad.oldScript; // Replace with your old script source 3 | var newScript = g_scratchpad.newScript; // Replace with your new script source 4 | 5 | // Implement a custom 'diff' function to compare scripts 6 | var differences = diff(oldScript, newScript); 7 | 8 | gs.info('Script Differences:\n' + differences); 9 | })(); 10 | -------------------------------------------------------------------------------- /Script Version Differ/readme.md: -------------------------------------------------------------------------------- 1 | # Script Version Differ 2 | 3 | ## Overview 4 | 5 | The Script Version Differ is a tool designed to compare two versions of a script and highlight the differences between them. This can be extremely helpful for tracking changes, conducting code reviews, and ensuring version control in your ServiceNow scripts. 6 | 7 | 8 | ## Usage 9 | 10 | 1. **Input**: Paste the source code of the old script version into the "Old Script" text area and the source code of the new script version into the "New Script" text area. 11 | 12 | 2. **Comparison**: Click the "Compare" button to initiate the comparison process. 13 | 14 | 3. **Results**: The tool will display a visual diff highlighting the differences between the old and new script versions. Added lines will be in green, removed lines in red, and modified lines with a yellow background. 15 | 16 | 4. **Export**: You can export the diff results as a text file for documentation or code review purposes. 17 | 18 | ## Examples 19 | 20 | Here are some examples of how to use the Script Version Differ: 21 | 22 | ### Example 1: Comparing Two ServiceNow Business Rules 23 | 24 | Suppose you have two versions of a ServiceNow business rule (e.g., `business_rule_v1.js` and `business_rule_v2.js`) and you want to see the differences: 25 | 26 | 1. Paste the content of `business_rule_v1.js` into the "Old Script" text area. 27 | 28 | 2. Paste the content of `business_rule_v2.js` into the "New Script" text area. 29 | 30 | 3. Click "Compare" to see the differences between the two versions. 31 | 32 | ### Example 2: Code Review 33 | 34 | As part of a code review process, you can use the Script Version Differ to review changes made by a colleague: 35 | 36 | 1. Paste the original script (before changes) into the "Old Script" text area. 37 | 38 | 2. Paste the modified script (after changes) into the "New Script" text area. 39 | 40 | 3. Click "Compare" to identify what lines were added, removed, or modified. 41 | -------------------------------------------------------------------------------- /Script include function syntax/siFun.js: -------------------------------------------------------------------------------- 1 | // create Script function which can be accessed from both Server side and Client side scripts (GlideAjax) 2 | 3 | functionName: function (param1,param2) { 4 | try{ 5 | var pVar1 = (param1) ? param1 : this.getParameter('sysparm_param1'); 6 | var pVar2 = (param2) ? param2 : this.getParameter('sysparm_param2'); 7 | 8 | var result; 9 | var gr1 = new GlideRecord("tableName"); 10 | gr1.addQuery("field", "value"); 11 | gr1.query(); 12 | if (gr1.next()) { 13 | result = gr1.getValue("fieldName"); 14 | }else{ 15 | result = ''; 16 | } 17 | return result; 18 | } 19 | catch(err){ 20 | gs.info('Exception found in function functionName : '+err); 21 | } 22 | }, 23 | -------------------------------------------------------------------------------- /Service Portal/Widgets/Client-Server_Request-Response.js: -------------------------------------------------------------------------------- 1 | // Option for client.server.get 2 | var option = { 3 | action: 'ACTION_NAME', // not necessary to use 'action' keyword as is only for identifying different request on server script 4 | 'KEY_1': 'VALUE_1', 5 | 'KEY_2': 'VALUE_2', 6 | //.. 7 | }; 8 | 9 | // below $client is the controler parameter in widget 10 | // Make a GET request to the server with the specified option 11 | $client.server.get(option).then(function(response) { 12 | // Log the response data 13 | console.log(response.data); 14 | }); 15 | -------------------------------------------------------------------------------- /Service Portal/Widgets/server-template.js: -------------------------------------------------------------------------------- 1 | // basic template example for server acript 2 | try { 3 | 4 | // identifying different request using 'action' 5 | if (input && input.action === 'ACTION_NAME') { 6 | // assigning response to the request from return 7 | data.KEY_NAME = someCallback(); 8 | } 9 | 10 | } catch (e) { 11 | // Add an error object to the response data 12 | data.error = { 13 | name: e.name, 14 | message: e.message, 15 | fileName: e.fileName, 16 | lineNumber: e.lineNumber 17 | }; 18 | } 19 | 20 | function someCallback() { 21 | // put process or excution here 22 | return { 23 | 'KEY_1': 'RESPONSE_VALUE_1', 24 | //... 25 | }; 26 | } 27 | -------------------------------------------------------------------------------- /Service Portal/spModal/Form Modal.js: -------------------------------------------------------------------------------- 1 | if (typeof spModal != 'undefined') { 2 | // showing form using form widget 3 | spModal.open({ 4 | title: "MODAL_TITLE", 5 | widget: "form", // 'form' is a global widget which is used to show form using table name 6 | widgetInput: { 7 | table: "TABLE_NAME", // ex. 'incident' 8 | view: "FORM_VIEW", // optional parameter, using default view if not using it, ex. 'Major Incidents' 9 | sys_id: "RECORD_SYS_ID", // optional parameter to show specific record, ex. '6d744e3997343110f971ffb0f053af6f' 10 | }, 11 | buttons: [] // hide default buttons. 12 | }); 13 | 14 | } else { 15 | g_form.addErrorMessage("MESSAGE_HERE"); 16 | } 17 | -------------------------------------------------------------------------------- /Service Portal/spModal/Large Popup HTML Message.js: -------------------------------------------------------------------------------- 1 | if(typeof spModal != 'undefined'){ 2 | spModal.open({ 3 | "title" : "TITLE_HERE", 4 | "message" : "MESSAGE_HERE", 5 | "size" : "lg", 6 | "buttons" : [{label:'TEXT_TO_DISPLAY', primary: true}], 7 | "keyboard" : false, 8 | "backdrop" : "static" 9 | 10 | }); 11 | 12 | } else { 13 | g_form.addErrorMessage("MESSAGE_HERE"); 14 | } 15 | -------------------------------------------------------------------------------- /Service Portal/spModal/spmodal.md: -------------------------------------------------------------------------------- 1 | # Service Portal Basic Modal 2 | This represents TWO different syntax macros. Once for the html field and one for the client script field. BOTH macros must be used in their respective fields for functional code. 3 | 4 | ## HTML 5 | ``` 6 | 7 | 18 | 19 | 20 | 21 | ``` 22 | 23 | 24 | ## Client Script 25 | ``` 26 | //Set modal options 27 | var modalOptions = { 28 | templateUrl:'myModal.html', //Template URL, as indicated in HTML