Validating fields after user clicks a form button in Service Now

user2475677 picture user2475677 · Mar 3, 2014 · Viewed 7.5k times · Source

I am working on a change ticket form with two form buttons which are "Submit" and "Request Approval". Submit is a way of inserting the record in the table.However the ticket will only move forward when the user presses "Request Approval".

I want to impose certain restrictions ONLY when a user clicks on "Request Approval" . By restrictions I meaning prompting the user to fill the Planned Start Date , End Date. However no such message should appear when a user clicks on Submit.

One way of doing it is to put in a condition for visiblity through a UI action. But I want the button to visible at all times. Please help

Answer

Josh picture Josh · Mar 5, 2014

You can set the Request Approval UI Action to run on the client (Client checkbox), set the Onclick field to requestApproval(); and then use the following code as a guideline for your script body. This allows your UI Action to run in two stages. On the client, where you can write your validation logic, and on the server (triggered by the gsftSubmit) when your validation logic has succeeded.

There are a few UI Actions in the system by default that employ this kind of code. Search for UI Actions where "Script contains gsftSubmit" to see other examples.

function requestApproval(){
   // Do your client side validation here 

   if (g_form.getValue('comments') == '') {
      return false;  //Abort submission if your validation fails
   }

   //Call the UI Action and skip the 'onclick' function
   gsftSubmit(null, g_form.getFormElement(), 'request_approval'); 
   // MUST call the 'Action name' set in this UI Action. 
   // Make sure this name doesn't conflict with an existing 
   // UI Action if this is a custom action. 
}

//Code that runs without 'onclick'
//Ensure call to server-side function with no browser errors
if (typeof window == 'undefined')
   serverResolve();

function serverResolve(){
   change_request.state = 1; 
   // other server side actions you wish to take 
}