You are using an older browser that might negatively affect how this site is displayed. Please update to a modern browser to have a better experience. Sorry for the inconvenience!

Passing sObject to @future methods in Salesforce


Future Annotation:

The Future Annotation is used to execute a method asynchronously in Salesforce. For example, we can use the future method to make a Web Service callout from an Apex Trigger.  Methods with the future annotation must be static and can only return void data type. The parameter must beprimitive data types, arrays of primitive data types, or collections of primitive data types.

Example:

global class MyFutureClass {

 @future
 static void myMethod(String a, Integer i) {
   System.debug('Method called with: ' + a + ' and ' + i);
   // Perform long-running code
 }
}

For Making the callout from the future methods, we need to set (Callout = true)

Example:

@future (callout=true)

 public static void doCalloutFromFuture() {
  //Add code to perform callout
}

In this article, I have explained the steps to pass an sObject list to future methods. Normally, we cannot pass the sObject list to the future methods. We can only pass the primitive data types to the future methods, but by using the simple technique, we can overcome this limitation with Salesforce.

AccountTrigger

Trigger AccountTrigger_AT on Account (after insert){

   //Using JSON.Serialize method we can convert the account list to Json

String jsonString = json.serialize(Trigger.NEW);

  // Pass the JSON String to the Future method

AccountTriggerHandler_AC.processAccountData(jsonString);

}

AccountTriggerHandler_AC

Public class AccountTriggerHandler_AC

{
   @future

   public static void processAccountData(String jsonString){

 //deserialize the JSON to the Account List

      List<Account> accountList = (List<Account>)Json.deserialize(jsonString,List<Account>.class);

//Printing the Account List

System.debug(‘---Account List---’+’accountList);

   }

   }

Conclusion:

You can neither call a method annotated with future from a method that also has the future annotation, nor call a trigger from an annotated method that calls another annotated method. Methods with the future annotation can be neither used in Visualforce controllers in either get or set methods, nor in the constructor.

Reference: Salesforce Future methods