Difference between revisions of "Getting Started with the Java API"
imported>Aeric m (Text replace - ' getEnv(' to ' Functions.getEnv(') |
imported>Aeric |
||
Line 458: | Line 458: | ||
[[Category:Java API|1]] | [[Category:Java API|1]] | ||
[[Category: | [[Category:Learning Resources]] | ||
</noinclude> | </noinclude> | ||
}} | }} |
Revision as of 00:08, 2 June 2012
Get started with the Java API and learn how to use Support Classes, Objects and Calls in the example presented here.
- Learn more: Java API
Use these examples as a step-by-step tutorial to learn these basic skills:
- Create an Account Record and a Contact Record
- Update Records with this process:
- Create a Task to Send an Email Message and assign it to a User (task owner)
- Send an Email Message to the Contact, then Mark the Task as Completed
Be sure to use a Plain Text Editor to manipulate the code.
- For detailed descriptions of classes, objects and calls, see Java API
For a cut-and-paste version of all the code described in these step-by-step examples, see: Java API Sample
Add an Account Record
To add record using Java API, follow these steps:
- Set up a Parameters Object
- Call addRecord to add a new record
- Check the result by calling methods in an instance of a Result object
Set up a Parameters Object
Data is passed to the platform using a Parameters object. The Parameters object holds key-value pairs, where each key corresponds to a field name and each value corresponds to a field value in the database. Set the key-value pairs and then pass the Parameters object as an argument when the record is added.
To set up a Parameters Object, create an instance of Parameters to hold the key-value pairs for the record by calling getParametersInstance. This instance is named addAccountParams:
Parameters addAccountParams = Functions.getParametersInstance();
To see the fields that are defined in an object:
- Open a web browser and Login to the platform
- Click Designer > Data > Objects > {object} > Fields
- View the field list
Add the key-value pairs for the database fields to addAccountParams by calling Parameters.add:
addAccountParams.add("name","Hello World Account"); addAccountParams.add("number","0000001"); addAccountParams.add("city", "Orlando"); addAccountParams.add("country", "United States"); addAccountParams.add("county", "Marine County"); addAccountParams.add("phone", "222-222-2222"); addAccountParams.add("website", "www.helloworldaccount.com");
Call addRecord
To add a new record, call addRecord and pass it an object identifier and the addAccountParams object. The values you added to addAccountParams are written to the account record in the database.
Result accountAddResult = Functions.addRecord("ACCOUNT", addAccountParams);
Like addRecord, many of the Java API record handling calls have an objectID parameter the object is specified ("ACCOUNT" in this example). In the objectID parameter, specify the Object Type Identifier.
Check the Result
The addRecord code (as well as several other Java API calls) returns an instance of the Result class. It is possible to check member variables in the Result object by calling its methods. For example, the code below makes a Java API debug utility call, making a nested call to Result.getMessage which returns a string indicating whether the call succeeded.
Functions.debug("Result of addRecord for Account:" + accountAddResult.getMessage());
The string specified in the debug call is written to the debug log.
To view the Debug Log:
- Click Designer > Global Resources > Debug Log
- When the code runs, use the Debug Log to troubleshoot problems during development. Many other debug calls are included in these code samples.
Debug Example for addRecord
This example checks the return code of addRecord by calling Result.getCode, and takes some action, based on the return code:
- Return codes:
- less then zero (<0); the call is not successful
- greater than or equal to zero (>= 0); successful
If the call is not successful, make a Java API throwError call, otherwise make a Result.getID call and continue
if(accountAddResult.getCode() < 0) String msg = "Function: Add Account"; Functions.debug(msg + ":\n" + accountAddResult.getMessage()); // Log details Functions.throwError(msg + "."); // Error dialog else return accountAddResult.getID();
Add a Contact Record
Following the same process (as adding an Account record), now add a Contact Record:
- Set up a Parameters Object
- Create an instance of Parameters by calling getParametersInstance
- Check the Result
Parameters addContactParams = Functions.getParametersInstance();
Then set the key-value pairs in the Parameters instance:
addContactParams.add("first_name", "John"); addContactParams.add("last_name", "Smith"); addContactParams.add("description", "Contact for Hello World added."); addContactParams.add("email", "mia@financio.com"); addContactParams.add("flag_primary_contact", "true"); addContactParams.add("street", "12345 Lake st");
Call addRecord, specifying "CONTACT" as the object identifier and passing the Parameters object you set up above.
Result contactAddResult = Functions.addRecord("CONTACT", addContactParams);
Make a nested call to Result.getMessage to write to the debug log:
Functions.debug("Result of addRecord for Contact - John Smith:" + contactAddResult.getMessage());
Check the return code by calling Result.getCode:
if(contactAddResult.getCode() < 0) String msg = "Getting Started: Add John Smith"; Functions.debug(msg + ":\n" + contactAddResult.getMessage()); // Log details Functions.throwError(msg + "."); // Error dialog else return contactAddResult.getID();
Update Records
To update a record, complete these steps:
- Search for the Account and Contact Records
- Check the Result
- Process the Returned Records
- Relate the Account Record to the Contact Record
In this example, the Contact record that was created in the Add a Contact Recordexample is updated by associating it to the Account record created in the Add an Account Record example.
Search for the Account and Contact Records
Follow these general steps to search for records:
- Call searchRecords
- Check the result
- Process the returned records
First, create a variable to hold the record identifier.
String contactRecID = null;
When a record is added database, the platform assigns it a unique record identifier. The value of a record identifier is opaque and is of no interest to the typical user. However, several Java API calls use the recordID parameter.
To get a record identifier, request the record_id field when making a searchRecords call. Find more information about arguments in searchRecords.
This example calls searchRecords for the CONTACT object. In order, the parameters to searchRecords in this example are:
- name of the object
- names of the fields to retrieve which includes record_id
- filter string (in this case, the filter string specifies that last_name contains "Smith" (the same as for the contact record previously created)
Result contactSearchResult = Functions.searchRecords("CONTACT", "record_id,first_name,last_name,email", "last_name contains 'Smith'");
Check the Result
The result code for searchRecords works a little differently than for addRecord.
Debug Example for searchRecords
This example checks the return code by calling Result.getCode, and takes some action, based on the return code:
- Return codes:
- less then zero (<0); the call is not successful
- equal to zero (=0); no records found
- greater than zero (> 0); successful and the value of the return code is the number of records returned
This code sample assigns the result code to a variable, which then defines the following action:
- If not successful, an error dialog is displayed
- If the code is zero, then a message is written to the debug log
- If successful, then the code is the number of records returned
int contactSearchCode = contactSearchResult.getCode(); if(contactSearchCode < 0) { String msg = "Error searching CONTACT object"; Functions.debug(msg + ":\n" + contactSearchResult.getMessage()); // Log details Functions.throwError(msg + "."); // Error dialog } else if(contactSearchCode == 0) { Functions.debug("Contact:No records found using the search function in CONTACT."); } else { // If the code "falls through" here, it means records were returned // that need to be processed; use the value of the return code in // the next section ... }
Process the Returned Records
In earlier examples, the Parameters object was shown to hold name-value pairs for fields for when the addRecord call is made.
The searchRecords call uses the Parameters object, but in a different way - the searchRecords call returns the set of fields that were requested for each record that matches the search criteria as an array of Parameters objects.
To process each Parameters object in the search results, create an instance of ParametersIterator and then specify ParametersIterator.hasNext as the expression of a while loop.
The example resumes with the code "falling through" when checking the result code for searchRecords, meaning that the result code is greater than zero, which is the number of records returned.
The following code sample will:
- Create an instance of ParametersIterator by calling Result.getIterator
- Set up a while loop with ParametersIterator.hasNext as the expression to evaluate at each iteration; Within the while loop, the code will:
- Create an instance of Parameters by calling ParametersIterator.next
- Call Parameters.get, specifying record_id as the parameter to get the value of the record identifier field which is assigned to a variable named contactRecordId
- Make a Java API getRecord call with these parameters:
- Object identifier
- List of fields to get
- The record identifier which is contactRecordId in this case
- Make a nested call to Result.getParameters to get the value of the first_name field; Checks if it is equal to "John". If so, the contactRecordId is assigned to the variable named contactRecID and the code breaks out of the loop; The contactRecID variable is used later when calling updateRecord, addTask, and sendEmailUsingTemplate
{ // "Falling through" here means records were returned Functions.debug("Search for John Smith: Number of records found using search function in Contact:" + contactSearchCode ); ParametersIterator contactIterator = contactSearchResult.getIterator(); while(contactIterator.hasNext()) { Parameters contactParams = contactIterator.next(); String contactRecordId = contactParams.get("record_id"); Result getContactRecordResult = Functions.getRecord("CONTACT", first_name,last_name,flag_primary_contact,description", contactRecordId); String firstName = (getContactRecordResult.getParameters()).get("first_name"); Functions.debug("Result from getRecord:\n" + getContactRecordResult.getMessage()); Functions.debug("Return code from getRecord:" + getContactRecordResult.getCode()); Functions.debug("First name retrieved : " + firstName); if(firstName.equals("John")) { contactRecID = contactRecordId; break; } } }
Relate the Account Record to the Contact Record
As objects are manipulated in the platform (added, updated, deleted), associations between objects must be maintained.
For example, when a Contact is created, it must be related to an Account:
- In the platform user interface, objects are related using the Lookup field as described in Relating Objects Using Lookups
- In the Java API, objects are related in code by searching for an object and then using a field value that identifies the object to set a field in a related object
Define the Relationship between Objects In this example, the code searches for an Account and then uses the Account Number to set a field in the contact. When relating a record in the Account object to a record in the Contact object, these three key-value pairs are required to define the relationship:
- reference_type
- related_to_id
- related_to_name
The following code searches for an account where the name field contains the text string "Hello". The Account record is created in Add an Account Record. The code follows the same model for a Update Records: call searchRecords, check the result code, and loop to process the returned records.
The following code sample:
- Sets up a while loop with ParametersIterator.hasNext as the expression to evaluate at each iteration. Within the while loop, the code creates two instances of Parameters:
- The first instance is created by calling getParametersInstance and is named updateContactParams; This instance is used to update the contact record later
- The second instance is created by calling ParametersIterator.next and is called accountParams
- Calls accountParams.get, specifying record_id as the parameter to get the value of the record identifier field, which is assigned to a variable named accountRecordId.
- Makes a Java API getRecord call using accountRecordId as a parameter
- Makes a nested call to Result.getParameters to get the value of the name field
- Checks if the name is equal to "Hello World"; If it is, the code adds some name-value pairs to updateContactParams
- Assigns the accountRecordId retrieved in the previous account search to related_to_id (This is how record identifiers are used to relate one object to another in the Java API)
- Makes an updateRecord call, specifying contactRecID and updateContactParams as parameters, which updated the Contact record.
- Checks the result in the final lines of code in the same way that previous examples did.
Result accountSearchResult = searchRecords ("ACCOUNT", "record_id,name,number,primary_contact_id", "name contains 'Hello'"); int accountResultCode = accountSearchResult.getCode(); Functions.debug(" Account:Result message for search ALL Account Records is " + accountSearchResult.getMessage()); Functions.debug(" Account:Result code for search ALL Record is " + accountResultCode); if(accountResultCode < 0) { String msg = "Account could not be retrieved"; Functions.debug(msg + ":\n" + accountSearchResult.getMessage()); // Log details Functions.throwError(msg + "."); // Error dialog } else if(accountResultCode == 0) { Functions.debug("Account:No records found using the search function in ACCOUNT."); } else { Functions.debug("Search for Hello World: Number of records found using search function in Account:" + accountResultCode); ParametersIterator accountIterator = accountSearchResult.getIterator(); while(accountIterator.hasNext()) { Parameters updateContactParams = Functions.getParametersInstance(); Parameters accountParams = accountIterator.next(); String accountRecordId = accountParams.get("record_id"); Result getAccountRecordResult = Functions.getRecord("ACCOUNT", "name,description", accountRecordId); String accountName = (getAccountRecordResult.getParameters()).get("name"); Functions.debug("Result from getRecord on ACCOUNT:\n" + getAccountRecordResult.getMessage()); Functions.debug("Return code from getRecord on ACCOUNT:" + getAccountRecordResult.getCode()); if(accountName.equals("Hello World")) { Functions.debug("Account record ID:" + accountRecordId); updateContactParams.add("description", "Updating Contact"); updateContactParams.add("reference_type", "Account"); updateContactParams.add("related_to_id", accountRecordId); updateContactParams.add("related_to_name", accountName); Functions.debug("Updating contact record with id:" + contactRecID); Result contactUpdateResult = Functions.updateRecord("CONTACT", contactRecID, updateContactParams); if(contactUpdateResult.getCode() == 0) { Functions.debug("Account:Contact of the Account record updated successfully\n" + contactUpdateResult.getMessage()); } else { String msg = "Error updating contact"; Functions.debug(msg + ":\n" + contactUpdateResult.getMessage()); // Log details Functions.throwError(msg + "."); // Error dialog } } } }
Create a Task Record
This section shows how to add a task and associate it to the previously created contact record.
Set Up a Parameters Object
As with the records created earlier, the code starts by creating an instance of Parameters and then assigning key-value pairs to it.
The following code sample will:
- Set up Parameters; Note that the contact_id and reference_id keys are set to the contactRecID that was retrieved in the Search for the Account and Contact Records section, which associates the task with that contact
String taskRecordID = null; Functions.debug("Testing addTask"); Parameters addTaskParams = Functions.getParametersInstance(); addTaskParams.add("action_type", "Email"); //Set the frequency for this task to be every day addTaskParams.add("calendar_frequency", "1"); //Set the calendar type to be day addTaskParams.add("calendar_type", "5"); addTaskParams.add("contact_id", contactRecID ); addTaskParams.add("date_created", new Date()); addTaskParams.add("description", "Send email to set up an appointment to discuss the invoice."); addTaskParams.add("notify_complete", "In Progress"); addTaskParams.add("percentage_complete", "10"); addTaskParams.add("priority", "High"); //Associate this task to a record that already exists so it will be displayed in open activities //Add this task to a contact (associate the task to the contact record //by setting the reference ID and the reference type) addTaskParams.add("reference_id", contactRecID ); addTaskParams.add("reference_type", "CONTACT"); addTaskParams.add("status", "In Progress"); addTaskParams.add("subject", "Hello World - Invoice discussion:" + new Date()); addTaskParams.add("repeat_flag", "true"); addTaskParams.add("reminder_duration", "24");
The following code sample shows the call to addTask. In order, the parameters are:
- Subject of the task
- Date of the task
- Owner of the task which is set by making a nested call to getEnv which is a Java API utility call
- Parameters object
Result addTaskResult = Functions.addTask("CONTACT : Task for - " + contactRecID, new Date(), Functions.getEnv(ENV.USER.ID), addTaskParams); Functions.debug("Result of addTask" + addTaskResult.getMessage()); if(addTaskResult.getCode() != -1) { taskRecordID = addTaskResult.getID(); Functions.debug("Added task using addTask - ID : " + taskRecordID); } else { String msg = "Error adding Task"; Functions.debug(msg + ":\n" + addTaskResult.getMessage()); // Log details Functions.throwError(msg + "."); // Error dialog }
Check the Result
Like other Java API calls such as addRecord and searchRecords, addTask returns a Result object whose methods can be called to check the result of the call. If addTask does not succeed, Result.getCode returns -1.
Send an Email Message
This section shows how to send an email message to a contact.
The following code sample will:
- Get the record for the contactRecID (the contact named "John Smith")
Find more information about arguments in sendEmailUsingTemplate
Result getContactRecordResult = Functions.getRecord("CONTACT", "first_name,last_name,email", contactRecID); Functions.debug("Sending Email to contact of Hello World Account..with email address:" + (getContactRecordResult.getParameters()).get("email"));
The following code sample calls sendEmailUsingTemplate. In order, the parameters are:
- Related object identifier
- Identifier of the related record which is contactRecID that was retrieved previously
- To list which is set by making a nested call to Parameters.get to get the email address of the contact that was just retrieved
- Cc list which is set by making a nested call to Parameters.get to get the email address of the contact that was just retrieved
- Description (a text string)
- Identifier of a print template. This template is evaluated at run time, its template variables substituted, and then sent as the body of the message
- List of print template identifiers to send as attachments (not used in this example)
- List of document identifiers in your documents folder to send as attachments (not used in this example)
Result sendEmailResult = Functions.sendEmailUsingTemplate("CONTACT", contactRecID, (getContactRecordResult.getParameters()).get("email"), (getContactRecordResult.getParameters()).get("email"), "Sending Email to Hello World's Primary Contact - John Smith", "1869974057twn1678149854", "", ""); Functions.debug("Done with sending mail from Hello World account's Contact John Smith"); if(sendEmailResult.getCode() != 0) { Functions.debug("Error in sending email!" + sendEmailResult.getMessage()); } else { Functions.debug("Success on sendEmail, check inbox : " + sendEmailResult.getMessage()); //If email was sent successfully update the task to end the task Parameters updateTaskParams = Functions.getParametersInstance(); updateTaskParams.add("subject", "Email sent"); updateTaskParams.add("end_flag", 1); updateTaskParams.add("status", "Completed"); updateTaskParams.add("due_date", new Date()); Result updateTaskResult = Functions.updateTask(taskRecordID, addTaskParams); Functions.debug("Updated task using updateTaskResult - " + taskRecordID + " : " + updateTaskResult.getMessage()); }
Like other Java API calls such as addRecord and searchRecords, sendEmailUsingTemplate returns a Result object whose methods you can call to check the result of the call. When sendEmailUsingTemplate succeeds, Result.getCode returns zero (0).
Mark the Task as Completed
In this example, when the call to sendEmailUsingTemplate succeeds, the code creates an instance of Parameters and adds field-value pairs to it. Then the code calls updateTask specifying taskRecordID and the Parameters object as parameters. This updates the task that was added earlier, setting its status field to "completed".
Java API Sample
This code is a complex example of the use of Java code to take a series of actions, each based on the previous code section. For information on the use of this code, see: Java Code Data Policy Examples.
//Let us get started by adding an account in to your data base //The following shows you how to add a hello world account //Create parameters instance to add all the key value pairs for the record Parameters addAccountParams = Functions.getParametersInstance(); //add name of the account in to Parameters object addAccountParams.add("name","Hello World Account"); //add number in to Parameters object addAccountParams.add("number","0000001"); //add city in to the Parameters object addAccountParams.add("city", "Orlando"); //add country in to the Parameters object addAccountParams.add("country", "United States"); //add county in to the Parameters object addAccountParams.add("county", "Marine County"); //add phone in to the Parameters object addAccountParams.add("phone", "222-222-2222"); //add website in to the Parameters object addAccountParams.add("website", "www.helloworldaccount.com"); //Using the JAVA API - addRecord, add the account 'Hello World' in to your database //By passing the addAccountParams object to the addRecord, all the values you have //added in to the Parameters object will be populated in the account record Result accountAddResult = Functions.addRecord("ACCOUNT", addAccountParams); //Use the debug function to log the status of the addRecord API call Functions.debug("Result of addRecord for Account:" + accountAddResult.getMessage()); //Check the return code using the getCode() method of the Result class //When the code is less than zero the call was not successful if(accountAddResult.getCode() < 0) { String msg = "Function: Add Account"; Functions.debug(msg + ":\n" + accountAddResult.getMessage()); // Log details Functions.throwError(msg + "."); // Error dialog } //If the code is zero then the addRecord API call was successful else { //return accountAddResult.getID(); } //Now try to add a contact called John Smith to your data base //Create a Parameters object //Add key-value pairs to the created parameters object so you can pass your values to //the contact object you are creating in your Application Parameters addContactParams = Functions.getParametersInstance(); //The following lines of code add first, last names, description, email to the parameters //object addContactParams.add("first_name", "John"); addContactParams.add("last_name", "Smith"); addContactParams.add("description", "Contact for Hello World added."); addContactParams.add("email", "mia@financiocorp.com"); //Set the contact to be a primary contact addContactParams.add("flag_primary_contact", "true"); //add the address to the parameters object addContactParams.add("street", "12345 Lake st"); //Use the API - addRecord by specifying object to be 'CONTACT' and pass the parameters //object you have created above Result contactAddResult = Functions.addRecord("CONTACT", addContactParams); Functions.debug("Result of addRecord for Contact - John Smith:" + contactAddResult.getMessage()); //Check the return code using the getCode() method of the Result class //When the code is less than zero the call was not successful if(contactAddResult.getCode() < 0) { String msg = "Getting Started : Add John Smith"; Functions.debug(msg + ":\n" + contactAddResult.getMessage()); // Log details Functions.throwError(msg + "."); // Error dialog } else { //If the code is zero then the addRecord API call was successful // return contactAddResult.getID(); } //Now let us see how we can update the records that we have added in the above steps. //To update a record, we need to have the record ID. //To retrieve the record ID we should search for the record in the object using search criteria //with filters String contactRecID = null; //Using searchRecord API search CONTACT object to retrieve the contact you have added in //to your database //searchRecord API requires the object name in which we are searching, the fields to retrieve // so we can use them after a successful search //The last parameter of the searchRecord in the call below is the filter string which //checks if last_name contains Smith //Look in to Filter Language to get details on other operators to use in filter strings Result contactSearchResult = Functions.searchRecords("CONTACT", "record_id,first_name,last_name,email", "last_name contains 'Smith'"); //The result code from searchRecord gives you the number of records it has found int contactSearchCode = contactSearchResult.getCode(); //If result is less than 0 than there is an error, call was not successful if(contactSearchCode < 0) { // Some error happened. String msg = "Error searching CONTACT object"; Functions.debug(msg + ":\n" + contactSearchResult.getMessage()); // Log details Functions.throwError(msg + "."); // Error dialog } //If code is zero then no records were found else if(contactSearchCode == 0) { // No records found. Take action according to your business logic Functions.debug("Contact:No records found using the search function in CONTACT."); } //Any number greater than zero tells you the number of records that have been found using //searchRecord API else { //Records retrieved successfully Functions.debug("Search for John Smith: Number of records found using search function in Contact:" + contactSearchCode ); ParametersIterator contactIterator = contactSearchResult.getIterator(); //Search through the list of CONTACT records retrieved while(contactIterator.hasNext()) { // Take action according to your business logic //Get the records using the Iterator object in to Parameter object Parameters contactParams = contactIterator.next(); String contactRecordId = contactParams.get("record_id"); //Now let us use the getRecord function to retrieve the record that was returned in //the search result //getRecord function expects the Object name as the first parameter and //the list of fields to retrieve in second parameter, //the record ID of the record to be retrieved is the third parameter Result getContactRecordResult = Functions.getRecord("CONTACT", "first_name,last_name,flag_primary_contact,description" , contactRecordId); //getRecord API's result contains the record as a Parameters object. //The following line of code shows you how to retrieve fields from the Parameters object //Please note that you have to pass the fields in a comma seperated string in getRecord's //second parameter to bethat is part of the result able to work with them on a //successful getRecord String firstName = (getContactRecordResult.getParameters()).get("first_name"); //Continue to log messages to debug log to track the progress of your program Functions.debug("Result from getRecord:\n" + getContactRecordResult.getMessage()); Functions.debug("Return code from getRecord:" + getContactRecordResult.getCode()); Functions.debug("First name retrieved : " + firstName); //We are looking for a contact 'John Smith' //The above searchRecord API did a filter on the last name, the following line will do //a filter on the first name //So you will get the record ID of the contact for Hello World account if(firstName.equals("John")) { contactRecID = contactRecordId; break; } } } //Now that we have learned how to use addRecord and updateRecord, let us go a step further //to associate the two records we have added. We have one account - Hello World and //one contact - John Smith //The next step is to relate the contact John Smith to Hello World account //The following scenario is to make the contact John Smith the primary contact owner of //Hello World account //In order to do that we need the record IDs for both the objects which can be object by //using the searchRecord API //let us search in the ACCOUNT object for records that contain the word 'Hello' //The following function call - searchRecords shows how to search for a record in ACCOUNT object //filter is set on the 'name' field of the ACCOUNT object. //The following searchRecord shows you how to use another operator 'starts with' in your //filter string. Result accountSearchResult = searchRecords ("ACCOUNT", "record_id,name,number,primary_contact_id", "name starts with 'Hello'"); //Check the result code from the search on the Account object int accountResultCode = accountSearchResult.getCode(); Functions.debug(" Account:Result me ssage for search ALL Account Records is " + accountSearchResult.getMessage()); Functions.debug(" Account:Result code for search ALL Record is " + accountResultCode); //Result code that is less than 0 tells you that an error has occured //you can use throwError to report the error in the UI if(accountResultCode < 0) { // Some error happened. String msg = Account could not be retrieved"; Functions.debug(msg + ":\n" + accountSearchResult.getMessage()); // Log details Functions.throwError(msg + "."); // Error dialog } //If the error code equals zero than the searchRecord returned with no records else if(accountResultCode == 0) { // No records found. Take action according to your business logic Functions.debug("Account:No records found using the search function in ACCOUNT."); } //At this point your searchRecord has returned a result code of more than zero //which means that at least 1 record has been found //the result code will tell you the number of records that have been found using //search criteria else { //Records retrieved successfully - log them to debug log to track the results of your search Functions.debug("Search for Hello World: Number of records found using search function in Account:" + accountResultCode); //You now have a set of records, you need to iterate through them to get the record you //are looking for //Use the ParametersIterator to step through the records to get the record ID //First use the getIterator method of the Result class on the Result object to //get the list of records to iterate through ParametersIterator accountIterator = accountSearchResult.getIterator(); //Now use the ParamtersIterator hasNext method to check if there are more records while(accountIterator.hasNext()) { // Take action according to your business logic //Get the records using the Iterator object in to Parameter object Parameters updateContactParams = Functions.getParametersInstance(); //ParametersIterator's next() method give you the next record in the list Parameters accountParams = accountIterator.next(); //From the Parameter object get the record ID of the ACCOUNT object String accountRecordId = accountParams.get("record_id"); //Now that you have the record ID of the retrieved record from search result //use the getRecord API to get teh record by passing the fields that you would //like to work with Result getAccountRecordResult = Functions.getRecord("ACCOUNT", "name,description" , accountRecordId); String accountName = (getAccountRecordResult.getParameters()).get("name"); Functions.debug("Result from getRecord on ACCOUNT:\n" + getAccountRecordResult.getMessage()); Functions.debug("Return code from getRecord on ACCOUNT:" + getAccountRecordResult.getCode()); //Now check the entire name of the account to make sure you are working with //the 'Hello World' account if(accountName.equals("Hello World")) { //Add information to parameter object to //Build your Parameters object to be able to pass it to updateRecord API to update the //CONTACT record John Smith Functions.debug("Account record ID:" + accountRecordId); //To modify the description, add the key value pair to the Parameters object updateContactParams.add("description", "Updating Contact"); //Add key value pair for reference_type field so the reference type is defined //You can have couple of reference types for a contact - Account or Prospect //The following will define the reference type updateContactParams.add("reference_type", "Account"); //The following line will define the record ID of the Account's record with which //contact John Smith will be associated with updateContactParams.add("related_to_id", accountRecordId); Functions.debug("Updating contact record with id:" + contactRecID); //Now using the updateRecord API update the contact record so the contact //John Smith will become the primary contact owner of the Account 'Hello World' Result contactUpdateResult = Functions.updateRecord("CONTACT", contactRecID, updateContactParams); //Check the result code from updateRecord //If the code is zero then the updateRecord was successful and the record was updated if(contactUpdateResult.getCode() == 0) { //Log a message to the debug log Functions.debug("Account:Contact of the Account record updated successfully\n" + contactUpdateResult.getMessage()); } else { String msg = "Error updating contact"; Functions.debug(msg + ":\n" + contactUpdateResult.getMessage()); // Log details Functions.throwError(msg + "."); // Error dialog } } } } //Let us now add a task to send email to contact to talk about the product //You can add a task using the addTask function //Before calling the addTask function call we need to build the Parameters object //to contain the key-value pairs that need to be passed to the addTask function //To begin with let us add the action type to be email String taskRecordID = null; Functions.debug("Testing addTask"); //Create parameters instance Parameters addTaskParams = Functions.getParametersInstance(); //Set action type of the task to be email addTaskParams.add("action_type", "Email"); //Using the getEnv function let us assign the task to a user //params.add("assigned_id", Functions.getEnv(ENV.USER.ID)); //Set the frequency for this task to be every day addTaskParams.add("calendar_frequency", "1"); //Set the calendar type to be day addTaskParams.add("calendar_type", "5"); //The task is required to be associated with a contact so let us add a key value pair //to set a contact ID. addTaskParams.add("contact_id", contactRecID ); //params.add("created_id", Functions.getEnv(ENV.USER.ID)); //Set the date created of the task to be today's date addTaskParams.add("date_created", new Date()); //params.add("date_modified", new Date()); //Set description and the information in key value pair as well addTaskParams.add("description", "Send email to set up an appointment to discuss the invoice."); //params.add("due_date", new Date()); addTaskParams.add("notify_complete", "In Progress"); //Add key-value pair to set the percentage complete addTaskParams.add("percentage_complete", "10"); //Set priority to be High. //priority is a picklist. Check the picklist values and set the value to match the picklist addTaskParams.add("priority", "High"); //The task needs to be associated to a record that already exists so you can see it //We are adding this task to a contact so let us associate the task to the contact record //in the open activiites by setting the reference ID and the reference type addTaskParams.add("reference_id", contactRecID ); addTaskParams.add("reference_type", "CONTACT"); //Set Status addTaskParams.add("status", "In Progress"); //Set subject in key-value pair addTaskParams.add("subject", "Hello World - Invoice discussion:" + new Date()); //If you want the task to be repeated set the repeat flag addTaskParams.add("repeat_flag", "true"); //Reminder duration addTaskParams.add("reminder_duration", "24"); //Make the addTask function call by passing the required values and the above created parameters object //Watch the following line of code to see how the getEnv method is used to //associate the task being added to the current user ID //The getEnv can be use to retrieve the environment variables at various situations dynamically Result addTaskResult = Functions.addTask("CONTACT : Task for - " + contactRecID, new Date(), Functions.getEnv(ENV.USER.ID), addTaskParams); //addTask returns an object of type Result //You can get the status of the task you have added by checking the Result object //Get the message from the Result object by calling the getMessage method Functions.debug("Result of addTask" + addTaskResult .getMessage()); //You can retrieve the return codes by using the getCode() method of the Result object if(addTaskResult.getCode() != -1) { //Retrieve the ID of the task added from the result //to use it in the future based on your business requirements taskRecordID = addTaskResult.getID(); Functions.debug("Added task using addTask - ID : " + taskRecordID); } else { //A code of -1 means the addTask function did not execute properly String msg = "Error adding Task"; Functions.debug(msg + ":\n" + addTaskResult.getMessage()); // Log details Functions.throwError(msg + "."); // Error dialog } //Now let us try to see how we can work with the functionality of sending email //The following scenario demonstrates send email to the contact using the sendEmail function //To send email to the Hello World Contact - John Smith, we should be able to getRecord //So retrieve the contact - John Smith's record using getRecord function making //sure we are retrieving the contact's email address Result getContactRecordResult = Functions.getRecord("CONTACT", "first_name,last_name,email" , contactRecID); Functions.debug("Sending Email to contact of Hello World Account..with email address:" + (getContactRecordResult.getParameters()).get("email")); //Make the call to sendEmail function by associating the email with the Hello World //contact - John Smith Result sendEmailResult = Functions.sendEmailUsingTemplate("CONTACT", contactRecID, (getContactRecordResult.getParameters()).get("email"), (getContactRecordResult.getParameters()).get("email"), "Sending Email to Hello World's Primary Contact - John Smith", "1869974057twn1678149854", "", ""); Functions.debug("Done with sending mail from Hello World account's Contact John Smith"); //Check the result of sendEmail function to get the code //If code is not equal to zero then the sendEmail function failed if(sendEmailResult.getCode() != 0) { //Use Result class's getMessage() to log the error message to Debug Log Functions.debug("Error in sending email!" + sendEmailResult.getMessage()); } //getCode returns zero then the sendEmail function was successful else { Functions.debug("Success on sendEmail, check inbox : " + sendEmailResult.getMessage()); //Let us now try to see how we can use updateTask API //The email was sent successfully so update the task you have added to end the task //Using the strategy we have used earlier let us create a Parameters object using //the Functions.getParametersInstance() function Parameters updateTaskParams = Functions.getParametersInstance(); //Add key value pairs to the Parameters object you have created in the line above //The task you have created using the addTask API will be updated //with the key value pairs you add to the Parameters object updateTaskParams.add("subject", "Email sent"); updateTaskParams.add("end_flag", 1); updateTaskParams.add("status", "Completed"); updateTaskParams.add("due_date", new Date()); //Using the updateTask API end the task you have created Result updateTaskResult = Functions.updateTask(taskRecordID, addTaskParams); Functions.debug("Updated task using updateTaskResult - " + taskRecordID + " : " + updateTaskResult.getMessage()); }