How to invoke a class from formscript using AJAX

Overview:

This utility shows how to send inputs to a JAVA class, perform operations in JAVA class and return the values which can be mapped with the object fields using a Form script or a  Field script.

Note: In this example, replace the values for tenant namespace, package name and class name with your environment values..

Class

To update the class information:

1. Go to Settings > Customization > Developer Resources.

2. Click Classes.

3. Click New Class.

4. Enter the following code:

package com.platform.tenantNameSpace.packageName;

import java.util.*;

public class className

{

  public Map methodName(Map params)throws Exception

    {

      // get params from form script

      String requestID = (String) params.get("param1");

      Map<String,String> returnMap = new HashMap<String,String>();

      returnMap.put("returnParamString", "returnParamStringValue");

      return returnMap;

    }

}


Form Script of an object to invoke a class:

To invoke the class listed in the preceding section, update the Form script as follows:

1. Go to Settings > Customization > Objects.

2. Select the object.

3. Click Forms.

4. Select a layout.

5. Click Form Scripts.

6. Enter the the following values in the On Load Script or On Save Script section.


var paramValue = "input value";
    var inputXML = "<platform>"
                 + "<execClass>"
                 + "<clazz>com.platform.tenantNameSpace.packageName.className</clazz>"
                 + "<method>methodName</method>"
                 + "<param1>" + paramValue + "</param1>"
                 + "</execClass>"
                 + "</platform>";

    // Use jQuery's ajax method to invoke the REST API
    $.ajax({
      type: 'POST',
      url: '/networking/rest/class/operation/exec',
      contentType: 'application/xml',
      Accept:'application/json',
      data: inputXML,
      dataType: 'json',
      success: function (data)
      {
        // Call succeeded.
        if (data.platform.execClass.returnParamString) {
           // Copy data to form fields.
           setTextFieldValue(_sdForm, "description", data.platform.execClass.returnParamString);
        } else {
           alert("No data returned.");
        }  
      } // End of success function
    }); // End of AJAX call