Play Games

Search This Blog

Sunday, February 18, 2018

How to pass trigger.new or trigger.newMap or trigger.oldMap to future method from trigger in salesforce.

In Salesforce we can use serialize and deserialize methods to pass required data from trigger to future method.

Simple Example below.
Apex Trigger Code:
trigger updatePhone on Account (after update) {
    String triggerNewList = JSON.serialize(Trigger.new);
    String oldMap = JSON.serialize(Trigger.oldMap);
    UpdatePhoneOnContact.updatePhone(triggerNewList,oldMap);
}

ApexClass Code:
public class UpdatePhoneOnContact {
    public static void updatePhone(String triggerNewList,String oldMap) {
        Set <Id> accountIdSet = new Set <Id>();
        Map <Id,String> accountMap = new Map <Id,string> ();
         List<Account> lstAccount = (List<Account>) JSON.deserialize(triggerNewList,List<Account>.class);
         Map<id,Account> accountOldMap = (Map<id,Account>) JSON.deserialize(oldMap,Map<id,Account>.class);
        for(Account acc:lstAccount) {
            if(accountOldMap.get(acc.Id).phone != acc.phone) {
                accountIdSet.add(acc.id);
            }
            if(acc.phone != null) {
                accountMap.put(acc.id,acc.phone);
            }
        }
        List <contact> contactList = new List <Contact>();
        for(Contact con:[select id,accountId,Phone from contact where accountId in:accountIdSet]) {
            if(accountMap != null && accountMap.containsKey(con.accountId)) {
                con.phone = accountMap.get(con.accountId);
                contactList.add(con);
            }
        }
        if(contactList.size() >0) {
            update contactList;
        }
    }
}

Enjoy Coding...

No comments:

Post a Comment