I have a scenario where, on insert of Events (Activities), I need to insert records related to the Events, and then tie them back to the Event by populating a custom field on the Event object with the Id of the corresponding newly created record.
In before update context, I would do something like this:
// Build Map
Map<Id,CustomObject__c> eventIdToObjMap = new Map<Id,CustomObject__c>();
for(Event record : recordList){
CustomObject__c obj = new CustomObject__c();
eventIdToObjMap.put(record.Id,obj);
}
// Insert New Values
insert eventIdToObjMap.values();
// Relate Back to Event
for(Event record : recordList){
CustomObject__c obj = eventIdToObjMap.get(record.Id);
if(obj != null){
record.CustomField__c = obj.Id;
}
}
However, in before insert context, we of course have no Id, which changes the approach.
I've considered using the sObject as the key, but, per the Apex Developer Guide under "sObject Map Considerations":
Be cautious when using sObjects as map keys. Key matching for sObjects is based on the comparison of all sObject field values. If one or more field values change after adding an sObject to the map, attempting to retrieve this sObject from the map returns null. This is because the modified sObject isn’t found in the map due to different field values. This can occur if you explicitly change a field on the sObject, or if the sObject fields are implicitly changed by the system; for example, after inserting an sObject, the sObject variable has the ID field autofilled. Attempting to fetch this Object from a map to which it was added before the insert operation won’t yield the map entry
So, my question is -
If I am just using the sObject key in the context of Trigger.new, scoped specifically to before insert context, and I am only manipulating the data of that Key object after I no longer need to reference it, should I consider this a safe option? Or should I just stick to an Integer index = 0
approach where I index each record during the loop with index++
and use the Integer for the map key? I just want to make sure there aren't any "gotchas" that I'm not thinking of that could cause the sObject to change, invalidating the key, outside of my own code.
after context
as well. You will haverecordId
in bothinsert
andupdate
scenario and then you can add a check to handle recursion. Won't this approach work for you?