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
sfdevnicksfdevnick 

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;
    }
 }

 

Message Edited by sfdevnick on 02-08-2009 09:17 PM
NaishadhNaishadh
It has to work. What error you are getting?
JmBessonartJmBessonart

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;
}

}

 

 

 

 

 J.

 

sfdevnicksfdevnick
Thank you both for your quick response. I apologize for not responding sooner, I have been off the grid knee deep in alligators working on an unexpected deadline. I'm hoping to be able to resume coding again in a few days, and will respond again then. Thank you for the code jm, I'm looking forward to testing it.