May 26, 2023

Before Business Rules in ServiceNow

There are four types of Business Rules in ServiceNow

  1. Before business rules
  2. After business rules
  3. Display business rules
  4. Async business rules

In ServiceNow, "Before" Business rules are a type of business rule that executes before a record is inserted or updated in the database. These rules allow you to perform actions and validations on the record data before it is saved.

Before business rules are defined with the condition "Before Insert" or "Before Update" and are executed in the order specified by their execution order values. They are typically used to enforce data integrity, perform calculations, set default values, or apply business logic before the record is saved.

Before business rules have the following characteristics:

  • Execution Order: Before business rules are executed in the order specified by their numeric values. Lower numeric values are executed first, while higher values are executed later. This order is important when multiple before business rules are defined for the same table and event.
  • Condition Evaluation: Before business rules evaluate conditions defined in their scripts to determine whether to execute the associated actions. Conditions typically involve checking field values, record state, or other criteria before proceeding with the desired actions.
  • Actions: When the conditions of a before business rule are met, the specified actions are executed. These actions can include modifying field values, performing calculations, displaying messages, or running additional scripts. Before business rules allow you to modify the record data before it is saved to the database.
  • Advance: This section allows to add additional execution condition and logic to manipulate and validate data before storing the data into the database.

Here are some key aspects of before business rules in ServiceNow:

  • Before Insert: A before business rule with the "Before Insert" condition is executed before a new record is inserted into the database. It allows you to perform actions and validations based on the values being inserted.
  • Before Update: A before business rule with the "Before Update" condition is executed before an existing record is updated in the database. It enables you to perform actions and validations based on the updated values.
  • Data Manipulation: Before business rules provide the ability to modify or manipulate record data before it is saved. You can set field values, validate data, perform calculations, or apply complex business logic to ensure data consistency and accuracy.
  • Field Validations: These rules can enforce data integrity by validating field values. You can check if required fields are populated, verify data formats, or validate against predefined criteria to ensure that only valid data is stored in the database.
  • Default Values: Before business rules can set default values for fields if they are not provided by the user. This feature allows you to automate the population of certain fields with predefined values, reducing manual effort and ensuring consistency.
  • Execution Order: The order of execution of before business rules is determined by their execution order values. Lower execution order values are executed first, while higher values are executed later. This order is crucial when multiple before business rules are defined for the same event or condition.

Before business rules play a vital role in manipulating and validating data before it is saved in ServiceNow. They allow you to enforce business rules, maintain data integrity, and ensure consistent data quality within the platform.

Before Business Rules provide flexibility and control over the data being saved to the database. They allow you to enforce data integrity, apply custom business rules, and modify data as necessary before it is persisted. By leveraging Before Business Rules effectively, you can ensure that data is accurate, consistent, and meets the desired criteria within your ServiceNow instance.


Example:

If the incident description is empty, the incident should not be submitted and display an information message.

Steps:

  • Create a before insert and update business rule on the incident table.
  • Add the condition "Description is empty".
  • In Action section check box the checkboxes and in the message textbox provide your message text.











Business Rules in ServiceNow

Within ServiceNow, business rules are an essential component used to define automated actions and behavior within the platform. Business rules in ServiceNow are server-side scripts that execute whenever a record is inserted, updated, deleted, or displayed. They allow you to define conditions and actions based on specific events or data changes within the platform. Business rules help automate processes, enforce policies, and maintain data integrity.

Business rules in ServiceNow play a vital role in automating processes, enforcing business logic, and maintaining data consistency across various applications and modules within the platform.

Here are a few key aspects of business rules in ServiceNow:

  1. Conditions: Business rules are triggered based on conditions specified in their scripts. These conditions evaluate data values, such as field values, to determine if the rule should be executed.
  2. Actions: When the conditions of a business rule are met, specified actions are executed. These actions can include setting field values, displaying messages, creating or updating records, or running additional scripts.
  3. Scope: Business rules can be defined at different levels within ServiceNow, such as at the global level or specific to a table or application. This allows for granular control over when and where the rules are applied.
  4. Order of Execution: Business rules are executed in a specific order determined by the numeric value assigned to them. Lower values are executed first, while higher values are executed later. This order is crucial when multiple business rules are defined for the same event or condition.
  5. Debugging and Testing: ServiceNow provides tools and logs to help debug and test business rules. Developers can review logs, debug scripts, and simulate rule execution to ensure they are functioning as intended.




There are four types of Business Rules in ServiceNow

  1. Query business rules
  2. Before business rules
  3. After business rules
  4. Display business rules
  5. Async business rules
To ensure smooth functioning, business rules have a designated execution order, determined by their assigned numeric values. Lower values execute first, while higher values execute later. This order is essential when multiple rules are defined for the same event or condition, preventing conflicts and ensuring proper sequencing.

Order of execution of Business Rules

  • Before business rules: Scripts configured to execute before the database operation with an order of less than 1000.
  • Before engines.
  • Before business rules: Scripts configured to execute before the database operation with an order greater than or equal to 1000.
  • The database operation (insert, update, delete).
  • After business rules: Scripts configured to execute after the database operation with an order of less than 1000.
  • After engines
  • Email notifications
  • After business rules scripts are configured to execute after the database operation with an order greater than or equal to 1000.


Best practices for Business Rules:

  • Understand Business Requirements: Gain a clear understanding of the business requirements before creating business rules. This helps ensure that the rules align with the desired outcomes and functionality.
  • Keep Business Rules Simple: Aim to keep business rules concise and focused on specific tasks. Avoid creating overly complex rules that may be difficult to maintain or understand. Splitting complex rules into smaller, more manageable rules can improve clarity and maintainability.
  • Prioritize Rule Execution Order: Set appropriate execution order values for business rules to control the sequence in which they are executed. Ensuring the correct order of execution prevents conflicts and ensures the expected behavior.
  • Use Server-Side Scripts Judiciously: Server-side scripts in business rules provide powerful capabilities but should be used judiciously. Excessive or inefficient script usage can impact system performance. Consider using client-side scripting where appropriate to offload processing to the user's browser.
  • Validate and Sanitize Data: Implement data validation checks within business rules to ensure data integrity. Validate user inputs, perform necessary data type checks, and sanitize data to prevent security vulnerabilities such as cross-site scripting (XSS) attacks.
  • Leverage Server-Side Conditions: Whenever possible, use server-side conditions in business rules rather than client-side conditions. Server-side conditions are more secure and reliable, as they execute on the server and are not subject to manipulation or bypassing by users.
  • Prevent Recursive Business Rules: Do not use current.update() in a Business Rule script. The update() method triggers Business Rules to run on the same table for insert and update operations, potentially leading to a Business Rule calling itself over and over. When a recursive Business Rule is detected, ServiceNow stops it and logs the error in the system log. However, this behavior may cause system performance issues and is never necessary.You can prevent recursive Business Rules by using the setWorkflow() method with the false parameter, current.setWorkFlow(false). This will stop Business Rules and other related functions from running on this database access. The combination of the update() and setWorkflow() methods is only recommended in special circumstances where the normal before and after guidelines mentioned above do not meet your requirements.
  • Use Script Includes Instead of Global Business Rules: Global Business Rules have no condition or table restrictions and load on every page in the system. Script includes only load when called. If you have already written a global Business Rule, move the function definition to a Script Include. 
  • Test and Debug Thoroughly: Thoroughly test business rules in different scenarios and user roles to ensure they behave as intended. Utilize debugging tools and logs provided by ServiceNow to identify and resolve any issues efficiently.
  • Document Business Rules: Maintain proper documentation for your business rules, including their purpose, conditions, actions, and any related dependencies. This documentation helps in understanding and maintaining the rules over time.
  • Regularly Review and Optimize: Periodically review your existing business rules to identify any redundant or obsolete rules. Remove or optimize rules that are no longer needed or that can be combined with others for better efficiency.
  • Follow ServiceNow Best Practices: Stay updated with the latest best practices and guidelines provided by ServiceNow. These recommendations evolve over time, so it's essential to keep track of any new guidelines and apply them to your business rule development.

In summary, business rules in ServiceNow are valuable tools for automating processes, maintaining consistency, and enforcing business logic within the platform. They contribute to enhanced efficiency and accuracy across various applications and modules.



Apr 16, 2017

Dynamically Move List Collector Options in ServiceNow

For basic information go to List Collector. My requirement was to populate List Collector dynamically on change of requested for.

Solution: List Collector or slashbucket stores values on basis of index values of left side options and index values in a list should be sorted.

var varName = 'u_app_name';
  var leftBucket = gel(varName + '_select_0');
  var rightBucket = gel(varName + '_select_1');
  var allOptions = leftBucket.options;
  
//on requested for change first clear rightBucket
  while(rightBucket.firstChild) {
                if(rightBucket.firstChild != null && rightBucket.firstChild != '') {
                    rightBucket.removeChild(rightBucket.firstChild);
                }
            } 
   
   //Get all the options from custom table
  var grApp=new GlideRecord('u_swo_application_list');
  grApp.query();
  
  while(grApp.next())
   {
   var exist=false;
   for(var i=0;i    {
    if(allOptions[i].value==grApp.sys_id)
     {
     exist=true;
    }
   }
   if(!exist){
   //add option to right side bucket
    var option = document.createElement("option");
    option.value = grApp.sys_id;
    option.text = grApp.u_application_name;
    leftBucket.add(option);
   }
  }
  sortSelect(leftBucket);
  allOptions = leftBucket.options;
  
  var selectedIDs =[];// new Array();
  
//custom table where storing right side slashbucket options   var gr=new GlideRecord('u_swo_leaver_and_joiner');
// caller is requested for value i.e sys_id
  gr.addQuery('u_requested_for.sys_id',caller);
  gr.addQuery('u_access',true);
  gr.query();
  var index=0;
  while(gr.next())
   {
   
   //selectedIDs[index]=index;//gr.u_application;
   for(var j=0;j    {
    
    if(allOptions[j].value==gr.u_application)
     {
     //insert index value only
     selectedIDs[index]=j;
     index++;
     break;
    }
   }
  }
//sort array
   selectedIDs.sort();
  moveSelectedOptions(selectedIDs, leftBucket, rightBucket,'-None-');
  sortSelect(rightBucket); 

Jun 21, 2014

FullCalender In Django

In this article i will demonstrate the use of FullCalendar in Django with its events.

<div id="calendar">

</div>

<div id='eventDialog' class='modal hide'>
       <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
              <h3 id="eventDialogLabel">Create Appointment</h3>
       </div>
       <div class="modal-body">
      
       </div>
        <div class="modal-footer">
              <button type="submit" class="btn btn-primary" id="submitButton">Save</button>
              <button class="btn btn-primary hide" id="deleteButton">Delete</button>
              <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
       </div>
</div>

<script type="text/javascript">

var startDate;
       var endDate;
       // allDay or not
       var appointmentType;
       var sourceFullView = { url: '/appointments/getappointments/' };
       var calendar=$('#calendar').fullCalendar({
              events: sourceFullView,
              defaultView:'agendaWeek',
              header: {
                     left: 'prev,next today',
                     center: 'title',
                 right: 'agendaWeek,agendaDay'
              },
              firstDay:1,
              slotDuration:'00:15:00',
              scrollTime:'07:00:00',
              selectable: true,
              selectHelper: true,
              editable: true,
              ignoreTimezone: false,
              lazyFetching:true,
              timezone:'UTC',
              select: function(start, end, allDay) {
                     eventType="";
                     $("#eventDialogLabel").html("New Appointment")
                     $("#eventID").val('')
                     $('#eventDialog').modal('show');
                     startDate=start;
                     endDate=end;
                     if(start._ambigTime) {
                           appointmentType=true;
                     }
                     else  
                           appointmentType=false;
                     $("#deleteButton").hide();
                      
              },
      
              eventClick: function(calEvent, jsEvent, view) {
                     eventType="";
                     $("#eventDialogLabel").html("Update Appointment");
                     $("#eventID").val(calEvent.id);
                     $("#deleteButton").show();
                     $('#eventDialog').modal('show');
                     startDate=calEvent.start;
                     endDate=calEvent.end;
                     if(calEvent.start._ambigTime) {
                           appointmentType=true;
                     }
                     else  
                           appointmentType=false;
                          
              },
              eventDragStart:function( event, jsEvent, ui, view ) {
                     eventType="eventDragStart";
                     startDate=event.start
              },
              eventDrop: function(event, delta, revertFunc) {
                     endDate=event.start;
                     EventDropOrResize(event);
              },       
              eventResize: function(event, delta, revertFunc) {
                     eventType="";
                     EventDropOrResize(event);
                    
              },
       });
       $("#deleteButton").on('click',function(){
              doPOST('DELETE');
              return false;
       });
       function EventDropOrResize(event)
       {
              $("#eventID").val(event.id);
              endDate=event.start;
              startDate=event.end;
              appointmentType=event.allDay
             
              doPOST("PUT");      
       }
       function doPOST(methodType)
       {
             
              $("#eventDialog").modal('hide');
              url="/appointments/getappointments/"
              if($("#eventID").val()!='')
              {
                     url+="?id="+$("#eventID").val();
              }
              var appointment={
            title_id: $("#id_title").val(),
            end:new Date(endDate),
            start:new Date(startDate),
                     type:$('#id_type').val(),
                     allDay:appointmentType
        }
              $.ajax({
                     type:methodType,
                     url:url,
                     datatype:'JSON',
                     data:JSON.stringify(appointment),
                     contentType: 'application/json; charset=utf-8',
                     async: false,
                     success:function(data){   
                           if(methodType=='DELETE')
                           {
                                  if($("#eventID").val()!='')
                                         $('#calendar').fullCalendar( 'removeEvents', [$("#eventID").val()] );
                           }
                           else if(data.id)
                           {
                                  if(data.id == $("#eventID").val())
                                         $('#calendar').fullCalendar( 'removeEvents', [data.id] );
                                  $('#calendar').fullCalendar( 'renderEvent', {id:data.id , title: data.title, start:  appointment.start,end:  appointment.end,allDay:appointment.allDay}, false);
                           }
                           else
                                  $('#calendar').fullCalendar('refetchEvents')
                     }     
              });
              return false;
       }

</script>
In views.py

def getappointments(request):
       try:
              if request.is_ajax():
                     id=request.GET.get('id')
                     if  request.method == "PUT":
                           # used to edit/delete appointments             
                           json_data=request.read()
                           data=json.loads(json_data)
                           if id:
                                  #logic to edit an appointment
                                  return JSONResponse({'id': appointment.id, 'title': appointment.title,'start':data['start'],'end':data['end'],'allDay': data['allDay']})
                           return JSONResponse("")
                     elif  request.method == "GET":
                           # used to get appointments
                           appointments=None
                                                             appointments=appointment.objects.filter().order_by('start')
                           return JSONResponse([{'id': o.id, 'title': o.title,'start':(o.start.isoformat()),'end':(o.end.isoformat()),'allDay':IsFullDayAppointment(o.start,o.end)} for o in appointments])
                     elif  request.method == "POST":
                           #used to save new appointments
                          
                           json_data=request.read()
                           data=json.loads(json_data)
                                  appointment=Appointment.objects.create(your fields……)
                           appointment.save()
                           return JSONResponse({'id':appointment.id, 'title': appointment.title,'start':data['start'],'end':data['end'],'allDay': data['allDay']})
                     elif request.method == "DELETE":
                           #used to delete appointments
                           if id:
                                  Appointment.objects.get(pk=id).delete()
                                  return JSONResponse("")
       except Exception, e:
              return JSONResponse(e.message)
def IsFullDayAppointment(startDate,endDate):
      
       d = endDate - startDate
       if d.days < 1 :
              return False
       else:
              return True

Now you can see the output













I hope this will help you.

Feb 7, 2012

How To Create Groups, Add Users In That Group And Give Permissions

SharePoint site security levels are assigned to Groups/Users. Users are added in different groups and each group is assigned security levels.
Security levels are assigned by the administrator who is adding the user. There are four levels by default.

* 
Full Control - Has full control. 
* 
Design - Can view, add, update, delete, approve, and customize. 
* Contributor - Can add content to existing document libraries and lists.
* 
Read - Can view pages and list items and download documents. 
* 
View Only - Can view pages, list items, and documents. Document types with server-side file handlers can be viewed in the browser but not downloaded. 

To add Groups in SharePoint site follow the following steps:

1. Go to your site and login with administrator. From Site Action choose Site Settings.


2. From Users and Permissions select Site Permissions and from ribbon click on  Create Group.

3. Give a name to user Group and choose the permission level. Click on save button.
 
If you want to change the permission level of existing Group, choose Grant Permissions in Step-2 and follow the following image and choose the permission level.
Add Users In Groups
4. Go to Site Action and Site Settings as in Step-1
5. From Users and Permissions select People and Groups and from left panel choose your Group in which you want to add users.Click on New->Add Users.
6. From pop-up window insert user name and check for existence. If user exists click OK button.