Skip to main content
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?
2 Antworten
  1. 17. Feb. 2017, 12:40

    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.