You need to sign in to do that
Don't have an account?
Trigger to pass master ID to object related to detail record
Hi, I'm new to Apex, trying to learn triggers, and would appreciate any help.
I have two custom objects "ObjectA" and "ObjectB". Both objects are on the detail side of Master-Detail relationships with Opportunity. ObjectB also has a lookup to ObjectA. When the user is on the main page for ObjectA, they can click on the button "New Object B" in the related list. In the edit screen for Object B that opens, the ID for ObjectA is of course pre-filled. I want to create a trigger that automatically fills the OpportunityID field in ObjectB with the same OpportunityID that already exists in the OpportunityID field in ObjectA.
Would the following work?
trigger SetOpportunityField on ObjectB__c (before insert, before update) {
for (ObjectB__c ob : Trigger.new) {
String cid = ob.ObjectA_ID__c;
List<ObjectA> ObjectAs = [SELECT OpportunityId FROM ObjectA__c WHERE Id = :cid];
ob.OppID__c = ObjectAs.get(0).OpportunityId;
}
}
Hi,
First, you can't do a SOQL into the FOR, because if Trigger.new (a list of ObjectB objects) have more than 20 records, the trigger throw a to many soql error (the limit is 20).
So you have to use maps to avoid doing the soql into the for. You can search for "bulk" trigger in the documentation.
trigger SetOpportunityField on ObjectB__c (before insert, before update) { List<Id> objectAIds = new List<Id>();
for (ObjectB__c ob : Trigger.new) {objectAIds.add(ob.ObjectA_ID__c);
}
Map<Id, ObjectA__c> objectAMap = new Map<Id, ObjectA__c>([SELECT OpportunityId FROM ObjectA__c WHERE Id in:objectAIds]);
for (ObjectB__c ob : Trigger.new) {
ob.OppID__c = objectAMap.get(ob.ObjectA_ID__c).OpportunityId;
}
}