I am creating some automation for a custom object "Handover". When the custom stage field is set to "Accepted", a new Opportunity should automatically be created and the Opportunity lookup field on the original Handover Record should be updated with the new Opp Id.

In the scenario that Handovers are updated in bulk, what would be the best/most effecient way to store each of the new Ids from the Opportunities and the update their Handover with the correct opp Id.

This is what I have so far:

public with sharing class HandoverTriggerHandler {
    public static void HandoverBeforeUpdateHandler(List<Handover__c> acceptedHandover) {
        List<Opportunity> HandoverOpps = new List<Opportunity>();
        for(Handover__c h: acceptedHandover){
            if((h.Handover_Status__c == 'Accepted') && (h.Opportunity_Generated__c = FALSE)){
                Opportunity o = new Opportunity();

                o.Description = h.Comments__c; 
                o.OwnerId = h.Assigned_Rep__c;  
                o.Primary_Contact__c = h.Contact__c;
                o.CloseDate = date.today();
                o.Name = 'Test Handover';
                o.stageName = 'Prospecting';
        Insert HandoverOpps;   

2 Answers 2


There are three key components you should keep in mind here.

  1. When you need to correlate one thing to another thing, your first thought should be to use a Map
  2. When an SObject (or a List<SObject>) is inserted, the records that were inserted will contain their newly created Ids (provided the DML didn't fail). This is one of only a few things that you get "for free" (i.e. you don't need to re-query the record)
  3. Things like SObjects are stored in collections (maps, lists, sets) as references

So, you can use the Id of your Handover__c record as the map key, and store the Opportunity you're generating as the value.

After you insert the Opportunities, they'll automatically have their Id field populated.

Because SObjects are stored in collections as references, the Opportunity stored in the map will also have the Id field populated.

You can then loop over your Handover__c list one more time, use the Id of the Handover__c record you're working on to pull the Opportunity from your map, and then get the (now populated) Id field from it.


You should need to use map for this implementation

public class HandoverTriggerHandler {
public static void HandoverBeforeUpdateHandler(List<Handover__c> contList){
    Map<ID,Opportunity> mapOfCt = new Map<ID,Opportunity>();
    for(Handover__c ct : contList){
        mapOfCt.put(ct.id,new Opportunity(name='test'));
        insert mapOfCt.values();
    List<Handover__c> updateHandoverList = new List<Handover__c>();
    for(Handover__c hang : contList){
            hang.opportunity__c = mapOfCt.get(hang.id).id;
        update updateHandoverList;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .