LogiUpSkill

Update Sets in Service-now

Update Sets in Service-now Update Sets 1. Update sets are used to capture the configuration data of a table. Update sets can be used to migrate the configuration data that has been done from one instance to another instance (example: from developer instance to test instance).   Configuration Data- Creating tables, fields, business rules, client scripts, choices etc. Normally we will consider the data in system tables, we consider as a configuration data.Normal Data: Creating records in incident, problem, user tables. Update_Synch table attribute 2. The tables for which UPDATE SYNCH attribute value will be true only for those tables the configuration data will be captured. 3. Since XML import and export can be used to migrate only one entry at a time, hence we use update sets which are capable of migrating the configuration records of multiple table at same time. 4. To create update setsGo to navigation -> update sets -> local update set -> new  Difference between Submit and Submit and make current: If we want to create the update set we can use the submit button but if we use submit and make current that update set will be created and will be made current i.e it will capture the modifications from that point of time.  Retrieved Update set: To obtain the captured information from other users update sets we can use this option. Steps: -> Go to update source in navigation search -> New -> Enter the values in fields – >Name: Other users update set name. – >URL: other users URL – >Username and Password: Other User’s credentials  Preview update set : To check whether the update set have been retried successfully or not.If successfully retrieved we can commit the changes and if there are any other errors it has to be rectified before the commit option can be used. …………………………………………………………………………………………………………………………………………….. Customer are not able to add the update_synch attribute on custom table, seems like user need to contact Servicenow only.

GlideDate in Servicenow

GlideDate in Servicenow gs.print(new GlideDateTime(“2011-08-01 12:00:00”).getDate()); var tt=new GlideDateTime().getDate();gs.print(tt); var ss=new GlideDateTime(“2017-11-04 12:00:00”).getDate();gs.print(ss); gs.print(Date()); …………………………………………………………………………. var g = new GlideDate();g.setValue(‘2015-01-01’);gs.info(g); var gDT = new GlideDateTime(g);gs.info(gDT); ……………………………………………………………………………………………………………. var gdt1 = new GlideDateTime(“2016-05-15”);var gdt2 = new GlideDateTime(gs.now());var dur = new GlideDuration(); var dur = GlideDateTime.subtract(gdt1, gdt2); //the difference between gdt1 and gdt2var temp = dur.getDisplayValue()gs.print(temp); var r= parseInt(temp);if(r==30 || r==60 || r==90){gs.print(“trigger”);}else{gs.print(“no”);} ……………………………………………………………………………………………………………………………………..   var gr = new GlideRecord(‘incident’);gr.get(‘784b900d4f4533001a0f45dba310c713’);var open= gr.opened_at;var gdt = new GlideDateTime(open);gdt.addDays(14);var due_date = gdt; gs.print(“Due Date After 14 days”+due_date); gs.print(“Numaric value for Open date”+gr.opened_at.dateNumericValue());   gs.print(“Open Date”+gr.opened_at); var tempp=gr.opened_at.dateNumericValue()+ 60000; gs.print(“final numaric value”+tempp); gr.opened_at.setDateNumericValue(tempp); gs.print(“Addding 60000 to Open date”+gr.opened_at.getValue());   ……………………………………………………………………………………………………………… var gdt1 = new GlideDateTime(“2019-04-24”); gs.print(gdt1); var gtime1 = new GlideTime();gtime1.setValue(“00:00:20”);gdt1.add(gtime1); gs.print(gdt1);   ………………………………………………………………………………………………………………………….. Javascript will not able give you the result without using time function var a = new Date(‘2013-11-05’);var b = new Date(‘2013-11-05’); if(a == b) {console.info(“a equals b”);}else {console.log(“a NOT equals b”);} if(a.getTime() == b.getTime()) {console.info(“a equals b”);}else {console.log(“a NOT equals b”);}

Workflow

Sub – Workflow Workflow is series of activities that follows execution path. An Activity is a collection of instructions that can include script, logging, approvals, record processing, timers, wait time, rollback activity etc. To create a workflow we need to go for workflow editor and we can drag and drop required activity in workflow. We can also drag and drop any other workflow in current workflow. We can create scratchpad variable to pass values from one activity to another. If we are using If activity then we can specify condition as follows- Following is the main workflow and we have added one sub workflow in main workflow. Sub Workflow- To send data from main workflow to sub workflow we need to create one input variable in sub workflow to hold value coming from main workflow as follows- We can specify input filed name, type, length etc as follows- Create scratchpad variable in main workflow Set value coming from main workflow to input variable Trainer Course To access value coming in input variable assign it to some other filed like short description To test this run the catalog item. Add Trainer name as Meghana. then automatically data present is scratchpad variable will be passed to sub workflow. After providing approval, check the workflow. short description should hold data coming from main workflow i.e. Service Now.   To send data back from sub workflow to main workflow we need to create scratchpad variable in sub workflow as follows – Then need to create return activity as follows and specify scratchpad variable as ${workflow.scratchpad.cost} Now go to main workflow and set map return value to as follows-   Then assign the value coming from sub workflow to description filed as follows, Main Workflow- Sub Workflow – Result- Incident Workflow Assignment Create Following Group’s 1.Email Group2.Phone Group3.Self Group4.Walk_in Group Create new state for Incident state field i.e. Waiting for Approval Incident Workflow         |         | Wait till the asigned to field should get value         |set state=Waiting for Approval         |         |Go for the approval according to Contact Type 1.Email ——Email Group2.Phone ——Group3.Self ——–Group4.Walk_in ——Group Any approval reject, it will go to run script activity where we should change the state=Canceled and then end the workflowAfter Approval         |         |         |Another approval should get trigger to Incident’s Caller’s ManagerIF the it reject , it will roll back to again the previous group approvalAfter approval it will go further         |         |         |Change the state=In Progress         |         |         |After this there should be 2 parallel process.1. if user canceled or closed the incident,then the workflow should end.2. if user changed the priority then put comments as “Priority changed” and go to Activity of Caller’s Manager Approval. but this priority changes can be done 2 times, if user is trying to do it for 3 times, then change the state=resolvedand end the workflow. Incident Form Field Task 1.Contact type field should have default value=Self Service2.User should not change the contact type field value once he submit the form3.User should not submit the form without categoy and subcategory field values Branch and Join        Branch flow Activity: The Branch activity is used to run the two activities parallel. The Branchactivity splits the workflow into multiple transition paths from a single activity. To add a transition path, select and drag the Branchactivity into the canvas. Then you can see the Branch activityproperties form displays, enter the branch name and click Submit to add the activity to the canvas, then click AddCondition. All transitions from this activity execute concurrently. This activity provides a single Always You can execute any number of transitions from this condition. Branching can affect the behavior of rollback activities.              Join flow Activity: The Join activity combines multiple execution paths into one transition path. To add Join to the canvas, Drag the join into the canvas and enter the name of join in the properties screenand click Submit. Use this activity for a workflow to wait for all activities in multiple paths to finish before it continuing. If multiple concurrentworkflow paths meet without a join activity, any subsequent activities execute two times. Connect incoming transitions from each activity you want to act as a predecessor to the Join activity. There will be two exit condition for the outgoing transitions: Complete and Incomplete. Complete: Joinexits along the Complete path when the system has determined that all predecessor activities havecompleted and transitioned to the Join. Incomplete: Joinexits along the Incomplete path when the system determines that at least one predecessor activitycompleted but transitioned along a path that bypassed the Join              Example: We have to set values for short description and description parallel when the wait for condition is true ->For that weuse Branch to run the two activity concurrently. We have to join two activity for approval user and approval group is approved then both condition satisfy it go toend -> For that we use Join to join that two activities.              Create Branch              Setting the values parallel for branch              Create approval user and group for join the activities              Create Join for two activities are approval user and approval group              Workflow for join and branch:              Output:              Branch output set the values for short description and description              Join output:              Once the user and group are approved the join go to end              Incomplete Join:              Usecase1:              If both approval user and approval group are approved then it show as complete. If approval user is approved and approval              group is rejected then it go as incomplete state.                Output for incomplete join:              Reject the approval for approval group and approved the approval user              Now it is in incomplete state then it go to end              If it is both are approved then it make as complete and go to end:              Usecase2:              If approval user is approved and approval group is rejected then it go incomplete then rollback condition

Server Side Script

Glide Aggregate – Scripting 1. To find no of records in table var g= new GlideAggregate(‘incident’); g.addAggregate(‘COUNT’); g.query(); var incident= 0; if(g.next()){ incident= g.getAggregate(“COUNT”); } gs.print(‘The Number of incidents are=’+incident); 2. To find no of incidents with caller Pallavi using addEncodedQuery var g= new GlideAggregate(‘incident’); g.addEncodedQuery(‘caller_id=681ccaf9c0a8016400b98a06818d57c7’);//Sys_id of Pallavi g.addAggregate(‘COUNT’); g.query(); var incident=0; if(g.next()){ incident=g.getAggregate(‘COUNT’); } gs.print(‘Number of incidents with caller Pallavi=’+incident); 3. To find no of incidents where assigned to field is not empty var g=new GlideAggregate(‘incident’); g.addNotNullQuery(‘assigned_to’); g.addAggregate(‘COUNT’); g.query(); var incident=0; while(g.next()){ incident=g.getAggregate(‘COUNT’); } gs.print(‘number of incident where assigned to field is not empty=’+incident); 4. To find no of incidents where assigned to field is empty var g=new GlideAggregate(‘incident’); g.addNullQuery(‘assigned_to’); g.addAggregate(‘COUNT’); g.query(); var incident=0; while(g.next()){ incident=g.getAggregate(‘COUNT’); } gs.print(‘number of incident where assigned to field is empty=’+incident); 5. To find number of incidents with state new var g=new GlideAggregate(‘incident’); g.addQuery(‘state’, ‘1’); g.addAggregate(‘COUNT’); g.query(); var incident=0; while(g.next()){ incident=g.getAggregate(‘COUNT’); } gs.print(‘number of incident with state new=’+incident); 6. To find number of incidents active true var g=new GlideAggregate(‘incident’); g.addQuery(‘active’, ‘true’); g.addAggregate(‘COUNT’); g.query(); var incident=0; while(g.next()){ incident=g.getAggregate(‘COUNT’); } gs.print(‘number of incidents=’+incident); 7. To find no of incidents with different category var g =new GlideAggregate(‘incident’); g.addQuery(‘active’,’true’); g.addAggregate(‘COUNT’,’category’); g.query(); while(g.next()){ category = g.category; categoryCount = g.getAggregate(‘COUNT’,’category’); } gs.log(“The are currently “+ categoryCount +” incidents with a category of “+ category);lideAggregate(‘incident’); g.addAggregate(‘COUNT’); g.query(); var incident= 0; if(g.next()){ incident= g.getAggregate(“COUNT”); } gs.print(‘The Number of incidents are=’+incident); 8. To find no of incidents with caller Pallavi using addEncodedQuery var g= new GlideAggregate(‘incident’); g.addEncodedQuery(‘caller_id=681ccaf9c0a8016400b98a06818d57c7’);//Sys_id of Pallavi g.addAggregate(‘COUNT’); g.query(); var incident=0; if(g.next()){ incident=g.getAggregate(‘COUNT’); } gs.print(‘Number of incidents with caller Pallavi=’+incident); 9. To find no of incidents where assigned to field is not empty var g=new GlideAggregate(‘incident’); g.addNotNullQuery(‘assigned_to’); g.addAggregate(‘COUNT’); g.query(); var incident=0; while(g.next()){ incident=g.getAggregate(‘COUNT’); } gs.print(‘number of incident where assigned to field is not empty=’+incident); 10. To find no of incidents where assigned to field is empty var g=new GlideAggregate(‘incident’); g.addNullQuery(‘assigned_to’); g.addAggregate(‘COUNT’); g.query(); var incident=0; while(g.next()){ incident=g.getAggregate(‘COUNT’); } gs.print(‘number of incident where assigned to field is empty=’+incident); 11. To find number of incidents with state new var g=new GlideAggregate(‘incident’); g.addQuery(‘state’, ‘1’); g.addAggregate(‘COUNT’); g.query(); var incident=0; while(g.next()){ incident=g.getAggregate(‘COUNT’); } gs.print(‘number of incident with state new=’+incident); 12. To find number of incidents active true var g=new GlideAggregate(‘incident’); g.addQuery(‘active’, ‘true’); g.addAggregate(‘COUNT’); g.query(); var incident=0; while(g.next()){ incident=g.getAggregate(‘COUNT’); } gs.print(‘number of incidents=’+incident); 13. To find no of incidents with different category var g =new GlideAggregate(‘incident’); g.addQuery(‘active’,’true’); g.addAggregate(‘COUNT’,’category’); g.query(); while(g.next()){ category = g.category; categoryCount = g.getAggregate(‘COUNT’,’category’); } gs.log(“The are currently “+ categoryCount +” incidents with a category of “+ category); Glide Record – Scripting 1. To find out number of active incidents var incident=new GlideRecord(‘incident’); incident.addQuery(‘active’, ‘true’); incident.query(); gs.print(“Row count =”+incident.getRowCount()); 2. To find out list of active incidents var incident=new GlideRecord(‘incident’); incident.addQuery(‘active’, ‘true’); incident.query(); gs.print(“Row count =”+incident.getRowCount()); gs.print(“List of Incidents”); while(incident.next()){ gs.print(‘Incident number’+incident.number); } 3. To find out no of incidents assigned to admin userid var gr= new GlideRecord(“incident”); var p= gs.getUserID(“admin”); gr.addQuery(“assigned_to”,p); gr.query(); gs.print(“No of incidents=”+gr.getRowCount()); while(gr.next()){ gs.print(gr.number); } 4. To find out no of incidents assigned to current user var gr= new GlideRecord(“incident”); var p= gs.getUserID(); gr.addQuery(“assigned_to”,p); gr.query(); gs.print(“No of incidents=”+gr.getRowCount()); while(gr.next()){ gs.print(gr.number); } 5. How many incidents with category hardware? var g= new GlideRecord(“incident”); g.addQuery(“category”,”hardware”); g.query(); gs.print(“No of incidents with category hardware=”+g.getRowCount()); while(g.next()){ gs.print(g.number); } 6. How many incidents with “Assigned To” value contains name admin? var gr=new GlideRecord(‘incident’); gr.addQuery(‘assigned_to.name’,’CONTAINS’,’admin’); gr.query(); var a= gr.getRowCount(); gs.print(a); while(gr.next){ gs.print(gr.number); } 7. Get all the incident which has Assigned to user having first name contains name admin word var gr= new GlideRecord(‘incident’); //gr.addEncodedQuery(‘assigned_toLIKEadmin’); //gr.addEncodedQuery(‘assigned_to.first_name.admin’); gr.addEncodedQuery(‘GOTOassigned_to.first_nameLIKEadmin’); /* var user= gs.getUserName(‘admin’); var admin=gr.addQuery(‘user’,admin); gr.addQuery(‘assigned_to’,user); */ //gr.addQuery(‘assigned_to’,’CONTAINS’,’admin’); gr.query(); while(gr.next()){ var count=gr.getRowCount(); } gs.print(count);   8. To find out number incidents which are resolved or closed var incident=new GlideRecord(‘incident’); incident.addQuery(‘state’, ‘6’).addOrCondition(‘state’, ‘7’); // resolved=6 and closed=7 incident.query(); gs.print(“Row count =”+incident.getRowCount());   9. Print first 4 Incident’s where caller’s first name start with Meghana var gr =new GlideRecord(“incident”); gr.addQuery(“caller.first_name”,”STARTSWITH”,”Meghana”); gr.orderBy(‘number’); gr.chooseWindow(0, 4); gr.query(); while(gr.next()){ gs.print(gr.number) } 10. Print the incident number using sys_id var gr = new GlideRecord(‘incident’); if (gr.get(’46cd8aaa2fe318104f7fdb9df699b604′))  //Sys id of record     gs.print(gr.number);   11. Print out first 4 incidents orderby number var gr = new GlideRecord(‘incident’); gr.orderBy(‘number’); // Ascending Order gr.chooseWindow(0, 4); gr.query(); while (gr.next()) {    gs.print(gr.number); } 12. Print 10 incidents by descending order of created date var gr = new GlideRecord(‘incident’); gr.orderByDesc(‘sys_created_on’);  // this will be descending order but by default will be ascending order and  gr.setLimit(10); gr.query();     while(gr.next()){ gs.print(gr.number); }   13. Delete the records from Table var gr = new GlideRecord(“incident”); gr.addQuery(“state”,3); //to delete all inactive incidents gr.query(); gr.deleteMultiple(); var gr = new GlideRecord(“incident”); //to delete one record if (gr.get(“SYS_ID_OF_RECORD”)) gr.deleteRecord(); Business Rule and Script Include Example Script Include and Business Rule Example: Business Rule: (After Insert) (function executeRule(current, previous /*null when async*/) {var createP=new ProblemUtils();var problemSysid=createP.createProblemRecord(current); //Create a Problem var getProblemRecrod=createP.getRecrodNumber(problemSysid,”problem”);  //get Problem Number createP.updateParent(getProblemRecrod,”problem”,current); // Update problem with Parent field gs.addInfoMessage(getProblemRecrod);})(current, previous);   Script Include:(Not Client Callable) var ProblemUtils = Class.create();ProblemUtils.prototype = {initialize: function() {}, createProblemRecord:function(current){ var createProblem=new GlideRecord(“problem”); // GlideRecord API is used to Query the table, Table name=problem createProblem.initialize(); // initialization of object createProblem.short_description=current.short_description + “Assingedto:” +current.assigned_to.name; //mapping createProblem.assigned_to=current.assigned_to; ////mapping createProblem.assignment_group=current.assignment_group; //mapping createProblem.description=current.description ; //mapping var problemSysid=createProblem.insert(); return problemSysid;}, getRecrodNumber:function (sysid,tableName){ var getNumber=new GlideRecord(“”+tableName);getNumber.addQuery(“sys_id”,sysid);getNumber.query();if(getNumber.next()){return getNumber.number;}else{ return “No Record found”;} }, updateParent:function(number,tableName,current){ var getNumber=new GlideRecord(“”+tableName);getNumber.addQuery(“number”,number);getNumber.query();if(getNumber.next()){getNumber.parent=current.sys_id;getNumber.description=current.number;getNumber.update();} }, type: ‘ProblemUtils’};

Client Scripting

Scripting   How to access last worknotes? We can use “current.comments.getJournalEntry(1)” to access last worknotes. hasRole() It returns true if the current user has the specified role or the admin role How to get system property? getProperty(“PROPERTY_NAME “); How to set system property? setProperty(“PROPERTY_NAME “, “property_value”); How to alert Assigned to user name from client script? var p=g_form.getReference(“assigned_to”).name; alert(p); How to access user data from client script g_user.userName g_user.userID g_user.firstName How to access user data from Server Side Script var firstName = gs.getUser().getFirstName(); var email = gs.getUser().getEmail(); getUser(); How to get sys_id from client script alert(g_form.getUniqueValue()); How to get current form table display value in client script alert(g_form.getDisplayValue()); and alert(g_form.getDisplayValue(“assigned_to”)) How to hide the related list from client script hideRelatedList(“REL:SYSIDOFRELATEDLIST”); How to hide section from script setSectionDisplay(“closure_information”, true); How to fire Event from Server-side script eventQueue(“EVENTNAME”, GlideRecord, Parm1, Parm2) How to write GlideRecord on incident to get active records Var gr=New GlideRecord(“incident”); addQuery(“active”,true); query(); if(gr.next()){ info(gr.number); } G-FORM:GlideForm.js is the Javascript class used to customize forms. getValue(‘short_description’) setValue(‘short_description’, “”) addOption(‘priority’, ‘2.5’, ‘2.5 – Moderately High’, 3) getTableName() addErrorMessage(‘This is an error’) addInfoMessage(‘The top five fields in this form are mandatory’) showFieldMsg(‘impact’,’Low impact response time can be one week’,’info’) showFieldMsg(‘impact’,’Low impact not allowed with High priority’,’error’) flash(“incident.number”, “#FFFACD”, 0) g_user: g_user is a global object in GlideUser, can only used in Client Script contains name and role information about the current user. userName userID firstName getClientData(“loginlanguage”) hasRole(‘admin’) hasRoleExactly(‘util’) hasRoleFromList(“itil, maint”) hasRoles() Client Script 1.To alert fullname of user: function onLoad() {        var p=g_user.getFullName();     alert(‘This is my first client Script= ‘+p); } 2.To alert If the Record is new or not: function onLoad() {     if (g_form.isNewRecord()){         alert(‘This is new Record’);     }     else{         alert(‘This is not a new record’);     } } 3.Use of different API’s: function onLoad() {     g_form.setReadOnly(‘u_email’,true);     g_form.setValue(‘u_description’,’hiiiiiii’);       g_form.clearOptions(‘u_category’);     g_form.getLabelOf(‘u_number’);     g_form.addInfoMessage(‘hi’);     g_form.setMandatory(‘u_first_name’,true);     g_form.setMandatory(‘u_last_name’,true);     if (g_user.hasRole(admin)){     g_form.removeOption(‘u_state’,’Maharashtra’);     } } 4.To make field visible after creating record but not while creating Record function onLoad() {    if(g_form.isNewRecord()){ g_form.setVisible(“u_convert_to”,false); }     else {         g_form.setVisible(“u_convert_to”,true);     } } 5.when Assigned To value changes, populte mail id of changed user in email field and populate user name in short description function onChange(control, oldValue, newValue, isLoading, isTemplate) {    if (isLoading || newValue === ”) {       return;    } var p=g_form.getReference(“u_assigned_to”).email;     g_form.setValue(“u_email”,p);     g_form.setMandatory(“u_first_name”,true);     g_form.setValue(“u_short_description”,’This is :’+g_user.getFullName()); } 6.when Assigned To value changes,populate user’s first name in short description function onChange(control, oldValue, newValue, isLoading, isTemplate) { if (isLoading || newValue === ”) { return;   } var p = g_form.getValue(“u_assigned_to”);     var name= g_form.getReference(“u_assigned_to”);     g_form.setValue(“u_short_description”, ‘This is’+name.first_name); alert(newValue); alert(oldValue);    } 7.Confirm details before submit form function onSubmit() {    //Type appropriate comment here, and begin script below    var a = g_form.getValue(“u_first_name”);     var b = g_form.getValue(“u_last_name”);     var con= confirm( ‘You Entered below datails-n The first name is- ‘+a+’n The last name is- ‘+b+’n  Do you confirm the details?’ );     if(con==true){         return;     }     else{         return 0;     } } 8. On Submit function onSubmit() {    //Type appropriate comment here, and begin script below     var p = g_form.getValue(“u_assigned_to”);     var name= g_form.getReference(“u_assigned_to”);     g_form.setValue(“u_short_description”, name.first_name); alert(p); }  9. On editing first name in list view (onCellEdit Client Script) function onCellEdit(sysIDs, table, oldValues, newValue, callback) {   var saveAndClose = true;     alert(sysIDs);     alert(table);     alert( oldValues);     alert(newValue);     alert(callback);  callback(saveAndClose);  } Advance Client Script Client Script: Client Side Objects: 1. G-FORM:GlideForm.js is the Javascript class used to customize forms. g_form.getValue(‘short_description’)g_form.setValue(‘short_description’, “”)g_form.addOption(‘priority’, ‘2.5’, ‘2.5 – Moderately High’, 3)g_form.getTableName()g_form.addErrorMessage(‘This is an error’)g_form.addInfoMessage(‘The top five fields in this form are mandatory’)g_form.showFieldMsg(‘impact’,’Low impact response time can be one week’,’info’)g_form.showFieldMsg(‘impact’,’Low impact not allowed with High priority’,’error’)g_form.flash(“incident.number”, “#FFFACD”, 0)   2. G-User: g_user is a global object in GlideUser. g_user is a Client Script Object and contains name and role information about the current user. g_user.userNameg_user.userIDg_user.firstNameg_user.getClientData(“loginlanguage”)g_user.hasRole(‘admin’)g_user.hasRoleExactly(‘util’)g_user.hasRoleFromList(“itil, maint”)g_user.hasRoles() Client Side Examples: 1. Problem Statement: For New Record show alert. function onLoad() { if (g_form.isNewRecord()){ alert(‘This is new Record’); } else{ alert(‘This is not a new record’); } } ……………………………………………………………………………………………………….. 2. Problem Statement: To make “Convert to” field visible after creating record but not while creating Record function onLoad() {   if(g_form.isNewRecord()){ g_form.setVisible(“u_convert_to”,false); } else { g_form.setVisible(“u_convert_to”,true); } } 3. Problem Statement: When Assigned To value changes, populte mail id of changed user in email field and populate user name in short description function onChange(control, oldValue, newValue, isLoading, isTemplate) { if (isLoading || newValue === ”) { return; } var p=g_form.getReference(“u_assigned_to”).email; g_form.setValue(“u_email”,p); g_form.setMandatory(“u_first_name”,true); g_form.setValue(“u_short_description”,’This is :’+g_user.getFullName()); } ……………………………………………………………………………………………………….. 4. Problem Statement: Confirm details before submit form function onSubmit() { //Type appropriate comment here, and begin script below var a = g_form.getValue(“u_first_name”); var b = g_form.getValue(“u_last_name”); var con= confirm( ‘You Entered below datails-n The first name is- ‘+a+’n The last name is- ‘+b+’n Do you confirm the details?’ ); if(con==true){ return; } else{ return 0; } } ……………………………………………………………………………………………………….. 5. Problem Statement: Hide the Clouser Information section from form while creating new record function onLoad() {//Type appropriate comment here, and begin script belowif(g_form.isNewRecord()){g_form.setSectionDisplay(“closure_information”, false);}else{g_form.setSectionDisplay(“closure_information”, true)}} ……………………………………………………………………………………………………….. 6. Problem Statement: Remove New state from the choice if it is not New function onLoad() {//Type appropriate comment here, and begin script belowif(g_form.getValue(“state”)==1){}else{g_form.removeOption(“state”,’1′);} } 7. Problem Statement: On change—Comments Make Work Notes Optional function onChange(control, oldValue, newValue, isLoading, isTemplate) {var requireOtherField = (newValue == ”);g_form.setMandatory(‘work_notes’, requireOtherField);} ……………………………………………………………………………………………………….. 8. Problem Statement: On Change- Work Notes Make Comments Optional function onChange(control, oldValue, newValue, isLoading, isTemplate) {var requireOtherField = (newValue == ”) ;g_form.setMandatory(‘comments’, requireOtherField);} 9. Problem Statement: If Caller is a VIP User then priority should be always P1. On Change Client Script on Caller Field function onChange(control, oldValue, newValue, isLoading, isTemplate) {if (isLoading || newValue === ”) {return;}g_form.getReference(‘caller_id’, priorityCallback); } function priorityCallback(caller){ if (caller.vip == ‘true’) {g_form.setValue(“impact”,1);g_form.setValue(“urgency”,1); }} ……………………………………………………………………………………………………….. 10. Problem Statement: Start date should be less than End Date,if not show alert Start date validation –function onChange(control, oldValue, newValue,

Incident Process in Service-now

Incident Process in Service-now We have incident where we have following process. We have following state for incident. New In Progress Pending Customer Pending Information Customer Update Resolved Closed Incident Process till Close New created incident in New State Fulfiller should ACK the ticket by clicking on ACK ui action and incident should go in “In Progress” state. Fullfiller can change the state to Pending customer to get information from user i.e. caller. When user i.e. caller send the information then incident state should changed to “Customer update” Fullfiller then change the state to In Progress. After resolving ticket fullfiller can change the state to Resolved. Fullfiller can cancelled the ticket when it is in In Progess. Fullfiller can Reject the incident before Acknowledgment. Fullfiller will not close the incident, to close the incident we have schedule job which will run daily. Incident Auto Close schedule job will close the incient which are in state=resolved the update date is less than 5 days of current date. Note: User can Cancelled the ticket by changing the state=Closed and closed code=Cancelled User can Reject the ticket by changing the state=Closed and closed code=Reject Close Code and Close Notes: When Incident changed the state to Resolved or Closed , Close Code and Closed Notes are mandatory fields. Close Code is choice field Close notes is String field. Close Code and Close Notes fields having more specific details about “Why we are closing the Incident.” SLA: Responce SLA start when incident is created and stops when Incident Acknowledged (If ACK_Time and ACK_By field has value then incident is acknowledged)Resolution SLA start when the incident is in “In Progress” and stops when incident is Closed and pause when incident is in one of the state i.e.Pending Customer, pending information, customer update and resolved.  Incident Priority: Priority field is always readonly and it is depends on urgency and sevirity fields using datalooup We have one client script i.e. if the caller is VIP, then the priority should be P1 using client script. Incident Assignment Rule We have assignment rules for setting assignment group as per Incident Category and Incident Subcategory  

ServiceNow Basics Questions & Answers

ServiceNow Basics Questions & Answers What is ServiceNow? ServiceNow is a cloud-based digital platform that used by organizations to automate, manage, and improve businesses processes, especially in IT Service Management (ITSM). What is User and its types? A User in servicenow is anyone who can log into the platform or who can access servicenow platform.1 Admin – Admin is a developer who is responsible for development.2 End User – A user who only uses application without any role assigned. He can raise the ticket/issue/request.3 ITIL user – fulfil the requst of end user.4 Maint user – Maint user is like a super admin.This user has access to acivate paid plugins.   What is Elevated Role? Elevate role is a role in which users will not get access after logging in. If the user needs that access, then the user needs to get that access manually. Why use Elevated Roles? To improve security and to follow best practice. To limit the amount of time someone has all admin privileges. What are the types of Table in ServiceNow? There are mainly four types of table in ServiceNow. sys_ table: This type of table is created by default. Only admin can access this table. This shown sys_user_role. Out of the Box Table : Name table is the table who starts with names like Incident, Practice. This tables are the existing tables. Sometimes they called out of the box tables. Custom Tables : The table we created by us called as customised table. After creating this it shown in “u_” table. It also called as user defined table. v_ table : this is the virtual table. allows you to display and interact with data from external systems as if it were a native table, without actually storing it in the ServiceNow database What is Dictionary overriding? Dictionary Override will come into a picture when we have a parent-child relationship between tables. By default, all fields and their attributes are inherited from parent table to child tables. Suppose you want to make a difference in one of the child tables for inherited fields then we will go for Dictionary override.  [Dictionary Override to allow a field in a child table to have a different behavior than the same field in a parent table]. We can override following properties: –  Override Reference Qualifiers Override Dependant Override Default Value Override Read Only Override Calculations Override Mandatory Override Attributes Override Display Values   What is Application Menu Application menu is the menu that organize and display modules. It is a group of related modules. Which means Incident is an application menu which has modules like, All -> Create new -> Open -> Assigned to me  They are located in left side of the interface which has in alphabetical order. Access based on roles, Which mean what you see depends upon what role you have. What is Update set? Update set is a component which is used to capture configurational changes and can be moved from one instance to another instance. We have update_sync property at table level. If it’s true, then the system will consider this table as a “configuration table”. So, whatever we are creating or updating records in that table will get captured into update sets.    What is Client script? Client script is a script that runs on client side (that is in users’ browser). Using Client script, we can change the look and feel of the form. Client Script is used to perform validations on forms.  There are four types of Client script: –  Onload – onLoad client script runs when the form is loaded.     onChange– onChangeclient script runs when the specific field value changes. OnChange client script will also run onLoad.   There are some parameters in onChange Script: control, oldValue, newValue, isLoading, isTemplate  onSubmit– onSubmit client script runs when the form is submitted.    onCellEdit-In a list view when we edit a particular cell value that time onCellEdit client script    There are some parameters in onCellEdit Script: sysIDs, table, oldValues, newValue, callback  How onChange client script run on onload client script? Normally when we are loading a form or new incident first the html structure will get loaded without values it means we don’t have any values on the form it is empty after that we will get the values from the database, and it will populate on the form. So, in this scenario values are getting change from empty values to database values. So, in this way, changing client script will run.  How to stop running the onchange Client script onload? function onChange(control, oldValue, newValue, isLoading, isTemplate)   {    if (isLoading || newValue === ”)   {      return false;  //when isLoading is false, the onChange script will not run on form load.   }  }  So, if isLoading is false that time onChange Client script will not load onLoad  . Difference between UI policy and Client script? UI policy UI policy is used in client side. Based on Condition we can make field mandatory, read only or visible. UI policy executes after Client Script Client script Client script executes before UI Policy  Client script can’t access the field which is not present on form  What is List Layout? A List Layout is the default configuration of columns and their order that users see when they open a list view for a specific table (like Incident, Change Request, etc.) in ServiceNow.  It’s essentially a global setting controlled by admins that defines:  Which fields (columns) appear in a list view  The order of those columns  Difference between list layout and Personalized list? Feature  List Layout  Personalized List  Affects  All users  Individual user  Requires admin role  ✅ Yes  ❌ No  Used for  Setting default list columns and order  User-specific adjustments  Changes saved  In the system list configuration  In user preferences  What is Business Rule? A Business rule is a server-side component that runs on the server side. It runs when a record is Displayed, Inserted, Updated, Deleted, or Quired.   There are four types:  Before: It runs before a database operation; it allows modifications before the record is saved. We cannot use the current Update method. For example, if you apply for leave, it will first go to the database and see if you have any leave left. After: It Execute after a database operation, it is suitable for actions that depend on the saved records. For example, if you submit a leave application for one day and then your leave is still available in the database, one of them is submitted as a leave application.  Async: Asynchronous business rules will run after the after-business rule. Asynchronous business rules will run asynchronously; it will not hold system. It cannot access the previous object.  Display business rules will run when the values from the database are getting displayed on the Form. 

SCHEDULED JOB

Introduction In ServiceNow, Scheduled Jobs are used to run scripts automatically at a defined time or interval. They are commonly used for tasks like sending reminder emails, updating records, cleaning up old data, or monitoring SLAs. This blog explains: What a Scheduled Job is When to use it How it works One real-time example with script What is a Scheduled Job in ServiceNow? A Scheduled Job is a server-side script that runs: At a specific date and time Daily / Weekly / Monthly At regular intervals (for example, every 15 minutes) It runs in the background without user interaction. When Should You Use a Scheduled Job? Use a Scheduled Job when: You need automation based on time No user action is involved You want to run reports or checks regularly Common Use Cases Send daily or weekly reports Notify users about SLA breaches Auto-close old incidents Escalate tickets stuck in a state Scheduled Job Types in ServiceNow Run once – Executes only one time Repeat – Runs daily, weekly, or monthly Run at intervals – Runs every X minutes or hours Example Scenario (Real-Time Use Case) Requirement Send an email every day at 7:00 AM to the IT Manager listing all Incidents that are still Open for more than 3 days. Step-by-Step: Create Scheduled Job Step 1: Navigate to Scheduled Jobs System Definition → Scheduled Jobs → New Step 2: Fill Basic Details Name: Daily Open Incident Reminder Run: Daily Time: 07:00:00 Active: true Step 3: Script (Example Code) (function () {    var gr = new GlideRecord(‘incident’);    gr.addQuery(‘state’, ‘!=’, 7); // Not Closed    gr.addQuery(‘opened_at’, ‘<=’, gs.daysAgoStart(3));    gr.query();     var incidentList = ”;     while (gr.next()) {        incidentList += gr.number + ‘ – ‘ + gr.short_description + ‘n’;    }     if (incidentList != ”) {        gs.eventQueue(‘daily.open.incident.alert’, null, incidentList, ”);    }})(); Step 4: Email Notification Create an Email Notification: Table: Incident Event name:daily.open.incident.alert To: IT Manager Subject: Daily Open Incidents Older Than 3 Days Body: Hello Team, Below are the incidents open for more than 3 days: ${parm1} Regards,ServiceNow Output Every morning at 7:00 AM: Scheduled Job runs Checks for old open incidents Sends one consolidated email to the IT Manager Best Practices Always test scripts in Background Scripts first Avoid heavy queries during business hours Log messages using gs.log() for debugging Keep scheduled jobs simple and efficient Conclusion Scheduled Jobs are powerful automation tools in ServiceNow. With proper planning and scripting, they help reduce manual effort and improve operational efficiency.

UI Policy 

UI Policy UI Policy is a client-side configuration rule that dynamically controls the behavior of form elements (such as fields, sections, or related lists) based on specified conditions. It allows administrators to make fields mandatory, read-only, or visible/hidden without writing code, ensuring a better user experience and data integrity directly in the user interface. UI Policies apply to forms and execute them in the browser. They are stored in the ‘sys_ui_policy’ table, with associated actions in sys_ui_policy_action. A UI policy is a client-side rule that dynamically controls form behavior based on specific conditions. It allows administrators to easily make fields mandatory, read-only, or visible/hidden without writing code, improving user experience and data integrity by adapting the interface in real-time as users interact with the form. For more complex logic, UI policies can include optional scripts, but they are preferred over client scripts for simple UI changes due to faster performance and easier maintenance. Steps to create UI Policy: Go to Application menu and search UI policies under system UI find the UI Policies After searching and navigating it, and then creating a new entry, you will see a form like this. Here is a Simple explanation of the checkboxes present on this form: Active – Enables or disables the UI Policy. The policy works only when this is checked. Reverse if false – Reverses the UI Policy actions when the condition evaluates to false. On load – Executes the UI Policy when the form is loaded. On change – Executes the UI Policy when the specified field value changes. Global – Makes the UI Policy applicable across all views of the form. Inherit – Allows child tables to inherit this UI Policy from the parent table. Then, select the table on which the UI Policy needs to be applied. For example, as shown in the screenshot below, the Incident table is selected. Also, make sure to mention Short Description, as it is a mandatory field. After entering the details, do not submit the form directly. Instead, right-click on the top grey strip and select Save to save the form. After saving the form, you will see the Sections. Within these sections, you need to create UI Policy Actions for the field on which you want to apply the policy. Example: Since Incident is selected, choose the specific field on which you want to apply the UI Policy. Then, define how the policy should behave for that field—for example, set Mandatory = True, as shown here, to make the field mandatory. Here is the output shown below. UI Policies in ServiceNow are a powerful, no-code tool for dynamically controlling form behavior, such as setting fields to mandatory, read-only, or visible/hidden based on conditions. They enhance data quality, streamline user experience, and are the recommended approach for simple client-side UI modifications due to their superior performance and ease of maintenance compared to client scripts. For more advanced needs, UI policies can incorporate scripts, but for straightforward changes, they remain the efficient and preferred choice.

Retroactive Start SLA

Retroactive Start SLA Introduction: In ServiceNow, a retroactive SLA (more precisely, an SLA with Retroactive start enabled) is a configuration option in SLA Definitions that allows a newly attached SLA to “backdate” its start time to an earlier point on the task record (typically the task’s creation time or another specified date/time field), rather than starting the clock from the moment the SLA attaches. Definition: Retroactive Start allows an SLA to begin counting from an earlier time in the past, instead of starting only when the SLA conditions are met. Retroactive Start is a simple but powerful setting for SLAs in tools like ServiceNow. Normally, when an SLA gets attached to a ticket (for example, when the priority changes), the timer starts right at that moment, giving the team the full allowed time from then on. When you turn on Retroactive Start, the SLA timer goes back in time and starts from when the ticket was originally created. This means all the time that already passed before the SLA was attached counts against the deadline. So, if a lot of time has already gone by, the team has less time left — or the SLA might even breach immediately. It makes the measurement fairer because it treats the issue as if the stricter SLA was always there, reflecting how long the customer has really been waiting. Example: Ticket created on Monday at 10 AM (low priority, 48-hour SLA). On Wednesday at 10 AM (48 hours later), priority upgraded to critical (new 8-hour SLA attaches). Without Retroactive Start: New SLA starts Wednesday 10 AM. Team has full 8 hours until Wednesday 6 PM. With Retroactive Start (set to “Created” date): The new SLA pretends it started Monday at 10 AM. 48 hours have already passed, so it’s overdue immediately! (Or whatever time is left based on the new duration.) This pushes the team to act faster on escalated issues. Steps to create retroactive SLA In Application menu Search Service Level Management, in that find SLA Definitions After this we will go to form of the SLA: This checkbox is located in the Start Condition section. By default, this is unchecked; we have to click this to perform further operations. After Clicking on this checkbox, we will find the ‘Set Start to’ filed which have choices where this Retroactive SLA will start on which field. Here is the real time example how Retroactive start SLA works: In this, the only normal SLA triggered but when changing condition or where to start the retroactive SLA then only our SLA works. When change in condition here is the retroactive SLA will start and counts the whole time of that incident when it created. In short, Retroactive SLA makes time tracking fairer by backdating the SLA clock to the ticket’s creation and giving credit for past waiting times. It ensures accurate, realistic deadlines — especially when priorities change — reflecting how long the customer has truly been waiting, without unfair breaches.