function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Parsa MotamediParsa Motamedi 

Create a map of object and related object

Hi,

From a before insert trigger on opportunity, I want to get all the opportunities inserted, find their related contact record and populate a field on the contact record with its associated opportunity record.
It seems like a simple concept, and I know I have to use a Map to achieve this, but to minimize the number of SOQL queries, it becomes real tricky.

Any help would be appreciated!
Parsa
Best Answer chosen by Parsa Motamedi
Colton WehkingColton Wehking
Hi Parsa, here is some sample code that can set these fields using only 1 query
 
trigger OpportunityTrigger on Opportunity (after insert) {
    Set<Id> contactsToUpdate = new Set<Id>();
    
    for(Opportunity o : Trigger.New)
        contactsToUpdate.add(o.Contact__c);
    
    Map<Id, Contact> contactMap = new Map<Id,Contact>([SELECT Id, Latest_Opportunity__c FROM Contact WHERE Id IN :contactsToUpdate]);
    
    for(Opportunity o : Trigger.New)
        if(contactMap.get(o.Contact__c) != null)
        	contactMap.get(o.Contact__c).Latest_Opportunity__c = o.Id;
    
    update contactMap.values();
}

First collect the IDs of all the contacts that are going to be updated, then put them into a map of IDs and Contacts, set the Latest Opportunity, and finally update them. 

All Answers

Parsa MotamediParsa Motamedi
Also, my Opportunity object has a custom Contact__c field, a lookup to the associated contact record.
What I'm trying to fill is a field called Latest_Opportunity__c on the Contact record.
Colton WehkingColton Wehking
Hi Parsa, here is some sample code that can set these fields using only 1 query
 
trigger OpportunityTrigger on Opportunity (after insert) {
    Set<Id> contactsToUpdate = new Set<Id>();
    
    for(Opportunity o : Trigger.New)
        contactsToUpdate.add(o.Contact__c);
    
    Map<Id, Contact> contactMap = new Map<Id,Contact>([SELECT Id, Latest_Opportunity__c FROM Contact WHERE Id IN :contactsToUpdate]);
    
    for(Opportunity o : Trigger.New)
        if(contactMap.get(o.Contact__c) != null)
        	contactMap.get(o.Contact__c).Latest_Opportunity__c = o.Id;
    
    update contactMap.values();
}

First collect the IDs of all the contacts that are going to be updated, then put them into a map of IDs and Contacts, set the Latest Opportunity, and finally update them. 
This was selected as the best answer
Ajay K DubediAjay K Dubedi
Hi Parsa,

I have gone through your question. Please try below code - 
 
//Trigger
trigger UpdateContactTrigger on Opportunity (after insert) {
    if(Trigger.isInsert && Trigger.isAfter) {
        UpdateContactHandler.updateRecords(Trigger.new);
    }
}


//Handler Class
public class UpdateContactHandler {
    public static void updateRecords(List<Opportunity> oppListNew) {
        List<Opportunity> oppList = new List<Opportunity>([Select Id, Name, Contact__c, Contact__r.Latest_Opportunity__c From Opportunity Where Id In :oppListNew]); 
        Map<Id,List<Opportunity>> conMapWithOpportunities = new Map<Id,List<Opportunity>>();                        
        if(oppList.size()>0) {
            for(Opportunity opp: oppList) {
                if(conMapWithOpportunities.ContainsKey(opp.Contact__c)) {                    
                    List<Opportunity> oppListTemp = new List<Opportunity>();
                    oppListTemp = conMapWithOpportunities.get(opp.Contact__c);
                    oppListTemp.add(opp);
                    conMapWithOpportunities.put(opp.Contact__c, oppListTemp);
                } else {
                    conMapWithOpportunities.put(opp.Contact__c,new list<Opportunity>());
                    List<Opportunity> oppListTemp = new List<Opportunity>();
                    oppListTemp = conMapWithOpportunities.get(opp.Contact__c);
                    oppListTemp.add(opp);
                    conMapWithOpportunities.put(opp.Contact__c, oppListTemp);                        
                }
            }
        }
        Contact con = new Contact();
        List<Contact> conList = new List<Contact>();
        for(Id i: conMapWithOpportunities.keySet()) {
            for(Opportunity opp: oppList) {                
                if(opp.Contact__c == i) {
                    opp.Contact__r.Latest_Opportunity__c = opp.Name;
                    con = opp.Contact__r;
                }
            }
            conList.add(con);
        }
        if(conList.size()>0) {
            update conList;
        }
    }
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com