Functions

From LongJump Support Wiki
Revision as of 01:36, 4 June 2011 by imported>Aeric (→‎Add an Opportunity)

Designer > Logic > Functions

Warn.png

DEPRECATED: Functions have been deprecated. Existing functions can be edited, but it is no longer possible to create them. Instead of writing functions, the recommended practice is to write methods in Java Classes, in order to gain the benefits of an improved Development Experience.


A function is reusable Java code that can be called from:

  • Standard Java classes, to create custom business logic.
  • Data policies, to do sophisticated processing.
  • JSP pages, to enhance the operation of the page.

Writing Functions

Functions work exactly like methods in Java code, and are written as if coding a method body in a Java class. You can consider functions as your own personal library of Java code.

Functions are written as if you are writing the body of a method. The platform injects the code you write into a Java class, adds a method signature, compiles it, and stores the bytecode.

The following Java API classes are implicitly imported into functions:

Accessing Parameters

The Java API functionParams object contains key-value pairs for the parameters passed to the current function:

  • When making a exec call, it is possible to specify a Parameters object as an argument

Within a called function, access to the parameters is through the functionParams object. This example gets a parameter named number that was passed to the current function:

String accountNumber = functionParams.get("number");

Restrictions

The Java code in functions follows the same restrictions as in classes. A complete list of restrictions is available in the Governors section.

Calling a Function

Functions are invoked via exec, and take arguments passed in functionParams Objects.

Functions can be invoked from:


Calling a Function from a Data Policy

This example calls a function named calculate_estimated_profit which takes in account’s revenue and calculates the profit as 30% of the revenue.

float revenue = params.getFloat("revenue", 0.0);
Parameters params = Functions.getParametersInstance();
params.add("revenue", revenue);
float profit = Functions.exec("calculate_estimated_profit", params);

Calling a Function from a JSP Page

This example calls a someFunction from Java code embedded in a JSP page.

<%
  String result = someFunction();
%>

Calling a Function from a Class

This example shows calling a function named add_task from a class.

import com.platform.api.*;


import java.util.*;

public class ExecAddTask implements Controller
{
  public ControllerResponse execute(HashMap params) throws Exception
  {
      String action = (String)params.get("action");
      if(action == null || action.equals(""))
      {
          return null;
      }
      else
      {
         return addTasks(params);
      }
  }
  private ControllerResponse addTasks(HashMap params) throws Exception
  {
      ControllerResponse cr = new ControllerResponse();
      Result result = null;  
      try
      {
         Parameters addOptions = Functions.getParametersInstance();
         addOptions.add("object_id", "CASE");
         String objectID = (String)params.get("objectID");
         String recordID = (String)params.get("recordID");
         if (objectID!= null && !objectID.equals("") 
         &&  recordID!= null && !recordID.equals(""))
         {
                 addOptions.add("object_id", objectID);
                 addOptions.add("record_id", recordID);
          }
          Functions.exec("add_task", addOptions);
          Functions.debug("Message:" + result.getMessage());
          params.remove("action");
          cr.setData(result);
          cr.setTargetPage("ManageCases.jsp");
      }
      catch(Exception e)
      {
         cr.setTargetPage("ManageCases.jsp");
         cr.setMessage(e.getMessage());
         Functions.debug("Message:" + result.getMessage());        
      }
      return cr;
  }
}

Manage Functions

Lock-tiny.gif

Users that have the Customize Objects permission can Edit or delete an existing Function 

Edit an Existing Function

  1. Click Designer > Logic > Functions
  2. Select the function to edit
  3. Edit the following fields:
    Title
    Name of the Function
    Function Name
    Programmatic name of the Function; Only alphanumeric characters and underscore allowed; In this example, enter: add_task
    Description
    Description of the function, how it works, circumstances for use
    Function Button
    Optionally, add a function from a list of predefined functions, defined in Java API
  4. Edit the code in the editing area, then click the [Save] button to save the code or click [Cancel] to stop the process

Delete an Existing Function

  1. Click Designer > Logic > Functions
  2. Click the name of the function to delete
  3. Click the [Delete] button or click [Cancel] to stop the process

Function Code Samples

Warn.png

DEPRECATED: Functions have been deprecated. Use methods in Java Classes, instead.


These code samples illustrate Functions. The comments embedded in the code samples explain the functionality.

Log Activity

This example logs an activity for a given object identifier and activity identifier.

Functions.debug("Function: logActivity");
Parameters params = Functions.getParametersInstance();
params.add("subject", "Subject : Adding log call via function");
params.add("description", " This is a log call added via function");
params.add("status", "In Progress");
params.add("sales_notes", "Confirmed the project amount with the contact");
params.add("action_type", "Email");
params.add("contact_id", "2015353331");
//If you had a custom field in your Task object
//Go to the link Objects » Tasks to get the field name
//The display name of the custom field should not be used to update the field
//Get the name of custom field to udpate the field
params.add("custom11", "custom field update using function");
params.add("activity_type", "Fax");
params.add("notes", "Functions - logactivity");
Result result = Functions.logActivity("Adding an activity using logActivity via Custom Code", functionParams.get("object_id"), functionParams.get("id"),getEnv(ENV.USER.ID), params);
Functions.debug("Result from logActivity:" + result.getMessage());
return result.getMessage();


Close Tasks with Status Equal to In Progress

This example finds all the tasks whose status field contains "In Progress" for a given record identifier and changes the status to "Completed".

//This function closes tasks related to any record in any object
Functions.debug("Object :" + functionParams.get("object_id")+
    "\n Function : Search And Update Tasks for :"+ functionParams.get("record_id"));
String recId = functionParams.get("record_id");
//Search for all tasks that are associated with the CASE object
//The search filter is hard coded here to look for case
//But you can pass the search string dynamically to your Parameters
//object when you call this function     
Result result = Functions.searchRecords("TASK", "record_id,subject,status", "reference_type contains 'CASE'");
int resultCode = result.getCode();
Functions.debug(functionParams.get("object_id")+":Result message for searching TASKS is " + result.getMessage());
Functions.debug(functionParams.get("object_id")+" :Result code for searching TASKS is " + resultCode);
if(resultCode < 0)
 {
    // Some error happened.
    String msg = "Related Tasks could not be retrieved";
    Functions.debug(msg + ":\n" + result.getMessage());  // Log details
    Functions.throwError(msg + ".");                     // Error dialog
 }
 else if(resultCode == 0)
 {
   // No records found. Take action according to your business logic
   Functions.debug(functionParams.get("object_id")+" : No TASKS found using the search function.");
 }
 else
 {
    //Records retrieved successfully
    Functions.debug("Number of tasks found using search function:" + resultCode);
    //Iterate through the set of records found
    ParametersIterator iterator = result.getIterator();
    //Work with all the records retrieved using searchRecords API in a while loop
    while(iterator.hasNext())
    {
      // Take action according to your business logic
      //Get the records using the Iterator object in to Parameter object

      Parameters params = iterator.next();
      String taskID = params.get("record_id");
      Functions.debug(" TASK: TASKID is " + taskID);
      String subjectInfo = params.get("subject");
      Functions.debug(" Task Subject is: " + subjectInfo);
      String taskStatus = params.get("status");
      Functions.debug(" Task Status is " + taskStatus);
      //We need to check for the status of the task
      //If the task is 'In Progress', we will update it
      if(taskStatus.equals("In Progress")) {
        Result getRecordResult = Functions.getRecord("TASK", "subject,status,reference_id,reference_type", taskID);    
        Functions.debug("Result from getRecord:\n" + getRecordResult.getMessage());
        Functions.debug("Reference Id from getRecord: " + (getRecordResult.getParameters()).get("reference_id"));
        params.add("status", "Completed");
        params.add("end_flag", 1);
        params.add("ownerID", getEnv(ENV.USER.ID));
        params.add("assigned_id", getEnv(ENV.USER.ID));
        params.add("description", "Check Activity history for Completed tasks. ");
        params.add("subject", "Completing Tasks on Case Close!");     
        params.add("date_modified", new Date());
        params.add("action_type", "Email");
        //Check to see if the reference ID of the task 
        //Update the task only if the reference Id matches the current record ID        
        if(((getRecordResult.getParameters()).get("reference_id")).equals(recId))
        {
          Functions.debug("Related Task found!");
          Result updateTaskResult = Functions.updateRecord("TASK", taskID, params);    
          Functions.debug("Update Task Result:" + updateTaskResult.getMessage());
        }
      }
   }
}


Add and Update an Event

This example adds an event for a given object identifier.

Functions.debug("Function : Add & Update Event");
Parameters params = Functions.getParametersInstance();
params.add("reference_id", functionParams.get("record_id"));
params.add("reference_type", functionParams.get("object_id"));
params.add("description", "Check your calendar to make sure the event is recorded.");
params.add("start_date", new Date());
params.add("subject", "Calender - adding an appointment");
// the following line is optional;
// it demonstrates how you can use the getEnv function to retrieve the USER values
params.add("assigned_to", getEnv(ENV.USER.ID));

Result result = Functions.addEvent("Meeting! " + functionParams.get("object_id"), 
    getEnv(ENV.USER.ID), new Date(), 11, 15, 30, params);
Functions.debug("Result of addEvent: " + result.getMessage());

if(result.getCode() != -1)
{
   // Some code to populate the eventID.   
   //eventId is required to use updateEvent
   String eventID = result.getID();
   Functions.debug("Event ID for event added using addEvent:" + eventID);
   // code to add description to the Event.
   params.add("subject", "Weekly status meeting!!");
   Result result2 = Functions.updateEvent(eventID, params);
   Functions.debug("Result from updateEvent:" + result2.getMessage());
}
else 
{
   Functions.debug("Error in adding event" + result.getID());
}


Add an Opportunity

This example adds an opportunity record.

//An opportunity can be added to an account or to a contact or prospect
Parameters params = Functions.getParametersInstance();
params.add("name", "Opportunity-" + new Date());
params.add("close_date", new Date());
params.add("stage","Prospecting");
//Associating the opportunity with a contact 
//Make sure you modify the record ID in the next line
//of code to match your CONTACT's record ID
params.add("contact_id", "1072726531");

//The following lines of code show how to update lookup fields 
//Lookup fields can be updated
//during an add operation but the key-value pair should be the 
//lookup field name and the record ID of the record 
//'lookuptotestcustomizations' is the record identifier of a user-defined lookup field
//'account_id' is the record identifier of a system-defined lookup field
params.add("lookuptotestcustomizations", "1637926708");
params.add("account_id", "2101896782");

//Relate the opportunity to the ACCOUNT object using the function
params.add("related_to_type", "ACCOUNT");

//The record ID of the ACCOUNT object is being hard coded here
params.add("related_to_id", "2101896782");

if(!params.equals(""))
{
   Result addRecResult = Functions.addRecord("OPPORTUNITY_V2", params);
   Functions.debug("Opportunity Add Record:" + addRecResult);
   if(addRecResult.getCode() != 0)
   {
       String msg = "Error adding Opportunity";
       Functions.debug(msg + ":\n" + addRecResult.getMessage());  // Log details
       Functions.throwError(msg + ".");                     // Error dialog
   }
   else 
   {
       Functions.debug("Success on adding an Opportunity");
       requestParams.add("opportunity_id",addRecResult.getID());
   } 
}
else
{
	Functions.debug("Parameters object is null.");
}

Send an Email Message with a Template

This example shows how to use the sendEmailUsingTemplate Java API call to send an email message with a template.

String attachmentIdList = "";
Functions.debug("Within contract object");

// To associate the sendEmail activity to a particular record 
//Retrieve the record ID from the functionParams object
String recordID = functionParams.get("id");

//Retrieve the object ID from the funtionParams object
String objectID = functionParams.get("object_id");

//Log the record ID to the log
Functions.debug("Record ID of record from current object : " + recordID);

//Make the API call by passing the appropriate parameters
//For parameter explanations, check the JAVA API 
Result result = Functions.sendEmailUsingTemplate(objectID, recordID, "mia@financiocorp.com", "mia@financiocorp.com", "Testing sendEmail Using Template", "1869974057twn1678149854", "", "");

Functions.debug("Post sendEmail API call from current object: " + objectID);
if(result.getCode() != 0)
    Functions.debug("Error in sending email!" + result.getMessage());
else
    Functions.debug("Success on sendEmail, check inbox : " + result.getMessage());

Add Note and Relate it to a Record

This function adds a note to a record in an object.

Parameters noteParams = Functions.getParametersInstance();
noteParams.add("description", "Very important to keep track of what is going on using Notes.");
noteParams.add("title", "Add Notes!");
noteParams.add("reference_id", requestParams.get("record_id"));
noteParams.add("reference_type", requestParams.get("object_id");

//Currently the sample is relating the note to an object which has 'name' as an identifier field, for example, the 'name' field in the Account object
noteParams.add("reference_name", requestParams.get("name");
Result addNote = Functions.addRecord("NOTE", noteParams);
Functions.debug("Result of adding a NOTE:" + addNote.getMessage());
Functions.debug("Code from adding a note:" + addNote.getCode());