• Jim Lamberth
  • NEWBIE
  • 10 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 1
    Replies
This code (not written by me) references the Id of a record in a before insert trigger. I was always under the impression you couldn't do that, as there is no Id before the record is committed to the database.

But it works... the Campaign__c field is correctly set every time. So naturally my question is how does it work? Because of the Id reference, or in spite of it? Is this some well known feature of Apex that I should be aware of, or a flawed trigger that happens to do the right thing?

trigger RegionTargetSetCampaign on Region_Targets__c (before insert) {

    Map<Id,Id> regionTargetToCallingGuide = new Map<Id,Id>();
    
    for(integer i=0; i<Trigger.size; i++) {
        Region_Targets__c regionTarget = Trigger.new[i];
        regionTargetToCallingGuide.put(regionTarget.id, regionTarget.Campaign_Delivery__c);
    }
    
    Map<Id,Campaign_Delivery__c> callingGuideMap = new Map<Id,Campaign_Delivery__c>([SELECT id, Campaign__c FROM Campaign_Delivery__c WHERE id IN :regionTargetToCallingGuide.values()]);
    
    for(Region_Targets__c regionTarget : Trigger.new) {
        regionTarget.Campaign__c = callingGuideMap.get(regionTargetToCallingGuide.get(regionTarget.id)).Campaign__c;
    }
}
This code (not written by me) references the Id of a record in a before insert trigger. I was always under the impression you couldn't do that, as there is no Id before the record is committed to the database.

But it works... the Campaign__c field is correctly set every time. So naturally my question is how does it work? Because of the Id reference, or in spite of it? Is this some well known feature of Apex that I should be aware of, or a flawed trigger that happens to do the right thing?

trigger RegionTargetSetCampaign on Region_Targets__c (before insert) {

    Map<Id,Id> regionTargetToCallingGuide = new Map<Id,Id>();
    
    for(integer i=0; i<Trigger.size; i++) {
        Region_Targets__c regionTarget = Trigger.new[i];
        regionTargetToCallingGuide.put(regionTarget.id, regionTarget.Campaign_Delivery__c);
    }
    
    Map<Id,Campaign_Delivery__c> callingGuideMap = new Map<Id,Campaign_Delivery__c>([SELECT id, Campaign__c FROM Campaign_Delivery__c WHERE id IN :regionTargetToCallingGuide.values()]);
    
    for(Region_Targets__c regionTarget : Trigger.new) {
        regionTarget.Campaign__c = callingGuideMap.get(regionTargetToCallingGuide.get(regionTarget.id)).Campaign__c;
    }
}