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
Ankita Gupta 65Ankita Gupta 65 

Bulkify code in apex trigger

I have the following scenario-
I have 2 objects with master-detail relationship. Object A-Detail and object B-Master
On the trigger on Object A(before insert), I'd like to create a B record and add it to the A record. For instance-
trigger appendChild on A(before insert)
{
for(A aRecord : trigger.new)
{
B bRecord=new B(Name='xyz');
insert bRecord;
aRecord .field=bRecord.Id;
}
}
How can I bulkify this code to avoid DML insert inside for loop?
rajat Maheshwari 6rajat Maheshwari 6

Hi Ankita,

Hope you are doing great !!!

I would like to inform you that, In Master Detail Relationship, when you will try to create child record, then it will ask to fill relationship field related to parent. In short, Relationship field on child object is mandatory, without it you can not create child record (Detail record).

Thanks

 


 
Balayesu ChilakalapudiBalayesu Chilakalapudi
try like this,
trigger appendChild on A(before insert)
{
Map<A,B> abmap=new Map<A,B>();
List<B> blist=new List<B>();
List<A> alist=new List<A>();
for(A aRecord : trigger.new)
{
  abmap.put(aRecord,new B(Name='xyz'));
}
for(B b:abmap.values()){
   blist.add(b);
}
insert blist;
for(A aRecord :abmap.keyset()){
   aRecord.field=abmap.get(aRecord).Id;
}
}

Let us know if it helps.