Header Ads Widget

Opportunity Owner updated by Account update || interview stuff


Opportunity Owner updated by Account update



 Scenario: We have requirement like Account owner change and automatically change Opportunity owner also change with related object record should update.



Brief Introduction: We have Account ‘Abc’ and on this account we have more than 20 Opportunities. Every opportunity contains Sales record doesn’t matter how much. Owner of Account is ‘John’ and updated to ‘Sam’ so every record must be updated on this action.



Solution:We have written code on Opportunity after update trigger and code snippet is given below.



Trigger:

trigger OpportunityAfterUpdate on Opportunity (after update) {

//Call the class which contain actual logic code

new UpdateopptyOwner().updateOwnerChanged();

}



Class:

public class SSRUpdatesalesArea{

public void updateOwnerChanged (){

        List<String> opptyIds=new List<String>();

        Opportunity objOppty,oldObjOppty;

        List<Sales__c> updateSales = new List< Sales__c>();

        for(Integer i=0;i<Trigger.new.size();i++){

            objOppty=(Opportunity)Trigger.new[i];

            oldObjOppty=(Opportunity)Trigger.old[i];

            if(objOppty.OwnerId != oldObjOppty.OwnerId){

                opptyIds.add(objOppty.Id);

            }

        }

  Map<Id, Opportunity> opptyMap = new Map<Id, Opportunity>([Select Id, Name, OwnerId, Owner.Name from Opportunity WHERE Id in: opptyIds]);



    for(Sales__c  objSales :[Select Id,Opportunity_Name__c, Request_Processor_Name__c, Opportunity_Owner__c From Sales__c where Opportunity_Name__c in :opptyIds)]){

              objSales.Request_Processor_Name__c=((Opportunity)Trigger.NewMap.get(objSales.Opportunity_Name__c)).ownerid;

              objSales.Opportunity_Owner__c=((Opportunity)opptyMap.get(objSales.Opportunity_Name__c)).Owner.Name;

              updateSales.add(objSales);

            }



        if(updateSales.size()>0){

            database.update(updateSales,false);

            }

    }

}



Code Description: We have written condition for owner changed and put in List of String. Written SOQL and get opportunity Map from Oppty. We get the map of Oppty id’s than we get Sales records to update and put in list.

After getting list of Sales records update this list.

Conclusion:  We can update number of thousands records on change of owner.

Post a Comment

0 Comments