• rcox1.395963632170139E12
  • NEWBIE
  • 0 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 0
    Replies
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;
}
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;
}