Tuesday, 25 June 2019

Updating parent records when child records get closed

public  with sharing class UpdateAccountIfOpptyStatus {
  public static void Custtrigger(List<Opportunity> optyList){
        Set<ID> accountIdSet = new Set<ID>();
        List<Account> accList =new List<Account>();
        for(Opportunity opp:optyList){
            if(opp.AccountId != null){
                accountIdSet.add(opp.AccountId);
            }
        }
       
        if(!accountIdSet.isEmpty()){
           
            Map<Id,Account> accMap =new Map<Id,Account>([ select Id,Account_Opty_Status__c from Account where ID IN:accountIdSet ]);
           
            for(Opportunity opp : optyList) {
                Account  acc = accMap.get(opp.AccountId);
                if(opp.AccountId==acc.Id){
                    if(opp.Opportunity_Status__c=='Closed'){
                        acc.Account_Opty_Status__c='Opportunity closed';
                        accList.add(acc);
                    }
                    else if(opp.Opportunity_Status__c!='Closed'){
                        acc.Account_Opty_Status__c='InProgress';
                        accList.add(acc);
                    }
                }
            }
            Update accList;
           
        }
    }
}

No comments:

Post a Comment