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
rcox1.395963632170139E12rcox1.395963632170139E12 

Apex Master-Detail Update Trigger

Hello,

So I am trying to create an Apex Trigger that updates a Master-Detail field upon import. I have included a scenario to aide in explaining:

I am mass importing several custom objects (call it Object1) and this object has a lookup field (Lookup1) that will have a value already being imported. Lookup1 relates to a separate custom object (Object2) which has a separate lookup field (Lookup2). When I import Object1, I want the Trigger to update a Master-Detail field (Master1) on Object1 with the value from Lookup2. I am pretty new to Apex and tried my shot at the Trigger but am having issues and not sure if I am even close. Any guidance is greatly appreciated!

Code:

trigger updateField on Object1(before insert, before update){

  List<Object2> IFPIDs = new List<Object2>();
  for (Object1 obj: trigger.new){
   IFPIDs.add(obj.Lookup1);
  }

  List<Object2> IFP = new List<Object2>([select id, Lookup2 from Object2 where id in: IFPIDs]);

  for (Object1 obj: trigger.new){

    for (integer i = 0; i < IFP.size(); i++){

      if (IFP.Object2 == IFP[i].id){
        IFP[i].Master1 = Lookup2;
      }
    }
  }

  update IFP;
}
StooStoo
Below is a re-write of the trigger.

The biggest change is putting the collection of Object2 items into a map for simpler access.

Finally just look through the Trigger.new and look for the matching lookup1 id in the map. if it exists, apply the lookup2 field from the found Object2 to the Master1 field on Object1.

I hope this helps.

Thanks,
Stuart McVicar - Developer / Consultant
Mobile Cloud Now (http://www.MobileCloudNow.com)


trigger updateField on Object1(before insert, before update)
{
   List<Object2> IFPIDs = new List<Object2>();
 
   // Build list of Object2 IDs related to all the Object1s in the trigger
   for (Object1 obj: trigger.new)
   {
  IFPIDs.add(obj.Lookup1);
   }

// This is a map of Object2 objects where the key is the ID of the object
// This enables us to find the matching Object2 by the ID in Object1.Lookup1
   map<id, Object2> IFPMap = new map<id, Object2>([select id, Lookup2 from Object2 where id in: IFPIDs]);

// iterate through all the objects in the trigger
   for (Object1 obj: trigger.new)
   {
    // the Object2 that matches the ID in lookup1 on Object1
    Object2 lookup1_Object = IFPMap.get(obj.lookup1);
   
    // If we find a matching object then update the Master1 field with the contents of Lookup2
  if(lookup1_Object!=null)
         obj.Master1 = lookup1_Object.Lookup2;
   }
  
   // no need to perform insert or update
}