Wednesday, 14 November 2018

Create Given Number of Child records On Parent Creation


Let's say In Account there is a custom field called NumberofContacts__c(Number Data Type). While we are creating an Account, if we give the NumberofContacts__c as '5' then this trigger will be automatically creates 5 contact records.

NOTE: We can give the number up to 10,000 since the Governer Limits fire the following error.

System.LimitException: Too many DML rows: 10001

.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
trigger CreateGivenNoOfContacts on Account (After Insert) {
    Map<Id,Decimal>AccLocMap =New Map<Id,Decimal>();
    List<Contact>ConInsert = New List<Contact> ();
    for(Account acc : trigger.new){
        AccLocMap.put(acc.Id,acc.NumberofContacts__c);
    }
    
    for(Account acc : trigger.new){

        for(integer i=0; i<AccLocMap.get(acc.id); i++){
            contact con = New Contact();
            con.LastName = acc.Name + ' Contact';
            con.AccountId = acc.Id;
            ConInsert.add(con);
        }
    }
    
    Insert ConInsert;
        
}

No comments:

Post a Comment