Configure Custom Scripts for Form Rules

Configure Custom Scripts for Form Rules

Tabulated below are some of the sample scripts that can be performed as actions in request/change Form Rules.
Requirement
Script
Examples
Remarks
Alert (Requests & Changes)
await CS.alert(“message”);
await CS.alert("Alert message");
 
Confirm (Requests & Changes)
var confirm = await CS.confirm(“message”);
if(confirm){
}
else{
}
var confirm = await CS.confirm(“Do you want to proceed");
if(confirm){
}
else{
}
 
Page Redirect (Requests & Changes)
await CS.alert(options);
Page redirection for internal links
await CS.alert({
     title: "Redirection Alert",
     message: "You are being redirected to Request list view",
     button_options: {
         label: "Proceed",
         redirectTo: "/ui/requests"
     }
});
  
Page redirection for external links
await CS.alert({
     title: "Redirection Alert",
     message: "You are being redirected to an external website in a new tab",
     button_options: {
         label: "Proceed",
         redirectTo: "https://www.zoho.com",
         target: "_blank"
     }
});
Properties
1. title, message - defines custom text content to display in the alert’s title and message part.
2. button_options - defines redirection details.
label - defines the alert button’s label content.
redirectTo - defines URL for navigation. When redirecting to external links, ensure that the redirectTo property value contains the full URL, including the protocol. For example, using “www.zoho.com” is invalid and hence use “https://www.zoho.com”.
target [optional] - If left undefined, the redirection will take place in the current tab. Setting the value to “_blank” will open the specified URL in a new tab.
Get API (Requests & Changes)
await CS.API.get(“url”,”input_data”);
await CS.API.get('/api/v3/requests/technician/',{list_info:{search_criteria:{field:'roles.name',condition:'is',value:'SDAdmin'}}});
To make internal API calls
Hide Fields (Requests & Changes)
CS.hideField(fields)
CS.hideField(["level","priority","urgency"]);
 
Show Fields (Requests & Changes)
CS.showField(fields)
CS.showField(["level","priority","urgency"])
 
Disable Fields (Requests & Changes)
CS.disableField(fields)
CS.disableField(["level","priority","urgency"]);
 
Enable Fields (Requests & Changes)
CS.enableField(fields)
CS.enableField(["level","priority","urgency"]);
 
Mandate Fields (Requests & Changes)
CS.mandateField(fields)
CS.mandateField(["level","priority","urgency"]);
 
Non-Mandate Fields (Requests & Changes)
CS.nonMandateField(fields)
CS.nonMandateField(["level","priority","urgency"]);
 
Add Options (Requests & Changes)
CS.addOptions(field,options)
CS.addOptions("urgency",["100000000000007061","100000000000007067"]);
Ensure that they are Pick Type fields and an array.
Remove Options (Requests & Changes)
CS.removeOptions(field,options)
CS.removeOptions("status",["100000000000007061","100000000000007067"]);
Same as above.
Reset Options (Requests & Changes)
CS.resetOptions(fields);
CS.resetOptions(["priority","impact"]);
Same as above.
Clear Options (Requests & Changes)
CS.clearOptions(fields)
CS.clearOptions(["urgency"]);
CS.clearOptions(["urgency","priority"]);
Same as above.
Set a Field Value (Requests & Changes)
CS.setValue(field,value)
CS.setValue("subject","This is a test subject");
CS.setValue("urgency",{"name":"High","deleted":false,"id":"100000000000007061"});
CS.setValue("due_by_date", Date.now());
 
Get Field Values (Requests & Changes)
CS.getValue(field)
var status=CS.getValue("status");
var created_date=CS.getValue("created_date");   
 
To retain the existing field values and store them in a variable.
Clear Field Values (Requests & Changes)
CS.clearValue(fieldnames)
CS.clearValue(["priority","impact"]);
 
Set Criteria (Requests & Changes)
CS.setCriteria(<field_name>,<criteria>);
 
 
Set Tasks (Requests)
CS.setTasks(tasksArray)
CS.setTasks([{"id":"100000000000033123","value":"Task 1"},{"id":"100000000000033125","value":"Task 2"}]);
Applicable only for request templates configured with tasks.
Unset Tasks (Requests)
CS.unsetTasks(tasks)
CS.unsetTasks([{"id":"100000000000033123","value":"Task 1"},{"id":"100000000000033125","value":"Task 2"}]);
Same as above.
Show Tasks (Requests)
CS.showTasks(tasks)
CS.showTasks([{"id":"100000000000033123","value":"Task 1"},{"id":"100000000000033125","value":"Task 2"}]);
Same as above.
Hide Tasks (Requests)
CS.hideTasks(tasks)
CS.hideTasks([{"id":"100000000000033123","value":"Task 1"},{"id":"100000000000033125","value":"Task 2"}]);
Same as above.
Show Resources (Requests)
CS.showResources(resources)
CS.showResources(["resources.res_100000000000030756"]);
Applicable only for request templates configured with resource questions.
Hide Resources (Requests)
CS.hideResources(resources)
CS.hideResources(["resources.res_100000000000030756"]);
Same as above.
Set Date Constraint (Requests & Changes)
CS.setDateConstraint(<field_names>,<constraint>);
const current_time = new Date().getTime();

var thirty_days = 30*24*60*60*1000;

CS.setDateConstraint("scheduled_start_time",{minDate:current_time,maxDate:current_time+thirty_days});
Set constraints for date fields
Show Field Errors (Requests & Changes)
CS.showErrors({
field_name: <field_name>,
message: <message>,
error_key: <unique_error_identifier>
});
errors.push({
   "field_name": "scheduled_end_time",
   "message": "Duration of the Change scheduled must not exceed 30 days",
   "error_key": "scheduled_end_time_ERR1"
  });
  CS.showErrors(errors);
Display field specific error messages beneath the fields.

Note: Using CS.abort() to abort form submission after CS.showErrors() is unnecessary, as the form is automatically aborted after CS.showErrors().
Clear Field Errors (Requests & Changes)
CS.clearErrors({
    field_name: <field_name>,
    error_key: <unique_error_identifier>
});
 
Clear field specific error messages created with Show Field Error.
Get Local Data (Requests & Changes)
CS.dataStore.get(name)
CS.dataStore.get(“Technician");
Uses the form's local data storage which the other custom scripts, configured for the same form, can access and return the data mentioned in the parameter. If the parameter is not passed, all the data stored is returned
Set Local Data (Requests & Changes)
CS.dataStore.set(name,value)
CS.dataStore.set(“Technician",”John”);
Uses the form’s local data storage which the other custom scripts, configured for the same form, can access, and assign the data to the key mentioned in the parameter. By default, the dataStore contains the logged-in user’s information such as email, id, first & last name, photo url, etc which can be accessed by CS.dataStore.get(“CS_context”).
On Field Change (Requests & Changes)
await CS.onFieldChange(<field_name>,<cbk>);
 
Triggers actions on field change in forms
On Form Submit (Requests & Changes)
CS.onFormSubmit(<cbk>);
 
Triggers actions on submitting forms
Abort (Requests & Changes)
CS.abort(<value>);
 
Aborts form submission
Info
Please note that all the given scripts should end with CS.end();

Guidelines for Using CS.end() statement:   

When writing custom scripts, follow these guidelines to ensure smooth execution and proper completion handling:

Mandatory Completion Statement: Always conclude your script with a single CS.end() call to ensure all actions are processed properly.

Event Listener Completion: When using event listeners (like CS.onFieldChange or CS.onFormSubmit), include a single CS.end() within each callback function to mar¸k the end of the actions you want to perform for that event.

Single Use of CS.end(): Only use CS.end() once per section of the script, whether it’s at the end of the main script or within an event listener. Calling it multiple times in the same section is not recommended, as it can lead to unexpected results. Make sure all actions you want to complete are listed before your single CS.end() call.
Avoid Additional Statements After CS.end(): Although CS.end() doesn’t function as a return statement, it’s best not to place any additional actions after CS.end(). Doing so can cause unintended behaviors and makes the script harder to follow.

Example Script
  1.  // Set value for the impact_details field

  2. CS.setValue('impact_details', "Please provide additional impact details here");

  3. // Event listener for category field change

  4. await CS.onFieldChange("category", () => {

  5.    CS.setValue('description', "Default category has been updated");

  6.    CS.end(); // Single completion statement in the callback

  7. });

  8. // Event listener for form submission

  9. CS.onFormSubmit(async () => {

  10.    const subject = await CS.getValue('subject') || "Problem occurred";

  11.    CS.setValue('subject', "Ticket ID - " + Date.now() + ' : ' + subject);

  12.    CS.end(); // Single completion statement in the callback

  13. });

  14. // Single completion statement at the end of the script
  15. CS.end(); 
 
In this example, CS.end() is used once at the end of each event listener and once at the end of the main script. This ensures all specified actions are completed as intended. Avoid placing any further actions after CS.end() within the same section to prevent unwanted effects.
   

Sample Custom Scripts for Form Rules (Requests)   

Example 1: To check if onboarding date is 10 days after the current date
  1.  var on_date = await CS.getValue("udf_fields.udf_date1");

  2. var curr_date = Date.now();

  3. var diff =  Math.round((on_date.value-curr_date)/(1000*60*60*24));

  4. if(diff<10){

  5.       await CS.alert("OnBoarding process will take minimum 10 days time");

  6.       CS.clearValue('udf_fields.udf_date1');

  7. }

  8. CS.end(); 
 
Example 2: To abort form submit when the category satisfies a particular condition.
  1.  async function checkValueandAbort(){
  2. var category = await CS.getValue('category');
  3. if(category != null && category.name == 'Desktop Hardware')
  4. {
  5. await CS.alert('Aborting Form Submit since category is Desktop Hardware');
  6. CS.abort();
  7. CS.end();
  8. }
  9. else
  10. {
  11. CS.end();
  12. }
  13. }
  14. CS.onFormSubmit(function(){
  15. checkValueandAbort();
  16. });
  17. CS.end(); 
Example 3: To set subject as a combination of category and subcategory
  1.  var cat = await CS.getValue("category");

  2. var subcat = await CS.getValue("subcategory");

  3. if(cat !=null && subcat!=null){

  4. var sub = cat.name + subcat.name;
  5. CS.setValue("subject",sub);
  6. }

  7. CS.end(); 

Sample Custom Scripts for Form Rules (Changes)    

Example 1: Abort Form Submission Conditionally
  1.  async function checkAndAbort(){

  2. var stage = await CS.getValue("stage");

  3. var status = await CS.getValue("status");

  4. var back_out = await CS.getValue("back_out_plan");

  5. var sch_start = await CS.getValue("scheduled_start_time");

  6. var description = await CS.getValue("description");

  7. var change_risk = await CS.getValue("risk");

  8. if(((stage.internal_name = "planning" && status.internal_name == "planning_in_progress")

  9. && !(back_out.back_out_plan_description != null && sch_start != null && description != null

  10. && change_risk != null && change_risk.id != null))){

  11.   await CS.alert("Please enter value in following Back out Description, Scheduled Start, Description, Change Risk");

  12.   CS.abort();

  13. }

  14. CS.end();

  15. }

  16. CS.onFormSubmit(function(){

  17. checkAndAbort();

  18. });

  19. CS.end(); 
Example 2: Show Error on field if the scheduled range exceeds 30 days
  1.  var errors = [];

  2. var endTime = await CS.getValue("scheduled_end_time");

  3. var startTime = await CS.getValue("scheduled_start_time");

  4. if(endTime != null && startTime != null){

  5. if(Math.round((endTime.value-startTime.value)/(1000*60*60*24)) > 30){

  6.   errors.push({

  7.    "field_name": "scheduled_end_time",

  8.    "message": "Duration of the Change scheduled must not exceed 30 days",

  9.    "error_key": "scheduled_end_time_ERR1"

  10.   });

  11.   CS.showErrors(errors);

  12. }

  13. }

  14. CS.end(); 
Example 3: Scheduled Start/End date selection restriction
  1.  var created_time = await CS.getValue("created_time");

  2. var thirty_days = 30*24*60*60*1000;

  3. if(created_time != null){

  4. CS.setDateConstraint("scheduled_start_time",{minDate:created_time.value,maxDate:parseInt(created_time.value)+thirty_days});

  5. CS.setDateConstraint("scheduled_end_time",{minDate:created_time.value,maxDate:parseInt(created_time.value)+thirty_days+thirty_days});

  6. }else{

  7. const current_time = new Date().getTime();

  8. CS.setDateConstraint("scheduled_start_time",{minDate:current_time,maxDate:current_time+thirty_days});

  9. CS.setDateConstraint("scheduled_end_time",{minDate:current_time,maxDate:current_time+thirty_days+thirty_days});

  10. }

  11. await CS.onFieldChange("scheduled_start_time",scheduleStartConstraints);

  12. await CS.onFieldChange("created_time",createdTimeConstraints);

  13. async function scheduleStartConstraints(){

  14. var start_time = await CS.getValue("scheduled_start_time");

  15. if(start_time != null){

  16.   CS.setDateConstraint("scheduled_end_time",{minDate:start_time.value,maxDate:parseInt(start_time.value)+thirty_days});

  17. }

  18. CS.end();

  19. };

  20. async function createdTimeConstraints(){

  21. var start_time = await CS.getValue("scheduled_start_time");

  22. created_time = await CS.getValue("created_time");

  23. if(created_time != null){

  24.   CS.setDateConstraint("scheduled_start_time",{minDate:created_time.value,maxDate:parseInt(created_time.value)+thirty_days});

  25.   CS.setDateConstraint("scheduled_end_time",{minDate:created_time.value,maxDate:parseInt(created_time.value)+thirty_days+thirty_days});

  26.   if(start_time !=null){

  27.    CS.setDateConstraint("scheduled_end_time",{minDate:start_time.value,maxDate:parseInt(start_time.value)+thirty_days});

  28.   }

  29. }

  30. CS.end();

  31. }

  32. CS.end(); 
 
 
    • Related Articles

    • Form Rules

      Form Rules allow you to define rules to automate certain actions on form fields based on custom conditions. Supported Form Types: Incident request forms, service request forms, change forms, problem forms, and release forms. Form Rules are executed ...
    • Sync Rules

      Sync rules define the data to be synced from assets, users, or software installations to CMDB. The synced data is populated as CIs in CMDB and linked to the corresponding asset, user, or software. You can perform various actions on CIs and their ...
    • Custom Actions

      Custom actions refer to user defined actions that can be performed on different entities across modules. For a custom action to be performed on an entity, it should be used with automation rules, subject to the availability of support. The following ...
    • Business Rules

      Configure Business Rules Business rules are used to automate actions on a request that fulfill certain incoming criteria. The criteria for the rules are set using the request fields. Business rules can be used to automate actions on incident, ...
    • Custom Configurations

      Custom Configurations, like web tabs, store additional information that cannot be grouped under the pre-defined modules. Unlike web tabs, custom configurations are accessible only via Setup. Why create Custom Configurations instead of Web Tabs? The ...