Thursday, August 6, 2015

Passing Objects/sObjects to Future Annotated Methods

Future Method 

The future annotation is a great feature on the Salesforce Platform to allow you to execute custom logic asynchronously. I often use them to perform callouts within the context of a database trigger.  However, one of the restrictions of future annotations is that you can not pass sObjects or objects as arguments to the annotated method. I regularly use encapsulation to pass a collection of parameters, or even an sObject, but this won’t work in @future method:

But thankfully there is a way you can do using JSON serialize|deserialize methods.
public with sharing class InsertAccountFuture {
 public static void createAccountUsingFuturer () {
  List<String> lstAccount = new List<String>();
  Account a1 = new Account('Sample Acount1');
  Account a2 = new Account('Sample Acount2');
  Account a3 = new Account('Sample Acount3');
  lstAccount.add(JSON.serialize(a3));
  lstAccount.add(JSON.serialize(a2));
  lstAccount.add(JSON.serialize(a3));
  createAccounts(lstAccount);
 }
 @future
 static void createAccount(List<String> lstAccount) {
  List<Account> insAccounts=new List<Account>();
  for (String ser : lstAccount)
  {
   insAccounts.add((Account) JSON.deserialize(ser, Account.class));
  }
  if(!insAccounts.isEmpty()){
   insert insAccounts;
  }
 }
}

No comments:

Post a Comment