Wednesday, 28 December 2016

How To Get trigger OldMap in Future method

Have you ever ran into a situation like getting oldMap values in future call?. I ran into this situation so came here to post about "how to pass oldMap in Future method".

What is Future Method?.

A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you'd like to run in its own thread, on its own time.

Future method can be defined using @future annotation above the method beginning.

syntax for future method,


public class className{
      @future
      public static void methodName(){

      }
}

So, coming back to passing an oldMap to future method,

Trigger

trigger AccountTrigger on Account (after update)   
 {  
     set<Id> newaccountID = new set<Id>();
     set<Id> oldaccountID = new set<Id>();
     Map<Id, String> oldAccountName = new Map<Id, String>();

     for(Account accountToProcess : Trigger.new){
         Account oldAccount = Trigger.OldMap(accountToProcess.id);
         newaccountID.add(accountToProcess.id);
         oldAccountName.put(oldAccount.id, oldAccount.Name);
         //you can have another map to put whatever fields you want from old map and pass
     }
     className.futureMethodName(accountID, oldAccountName);
 } 


Future Method


global Class className
{
    @future
    public static void futureMethodName (set<Id> newAccounId, Map<Id, String> oldAccountName)
    {
     
        list<Account> newAccList = new List<Account>();
        for(Account newAccount :[select id,Name, Type from Account where id in:newAccounId])
        {
     
                if(newAccount .Name != oldAccountName.get(newAccount.id))
                {
                    newAccount.Name = newAccount .Name+' - New Account Name';
                      newAccList.add(newAccount);
                }
         }  
         if(newAccList.size() > 0){
               update newAccList;
         }
   }