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
bhupal reddy 7bhupal reddy 7 

How to insert multiple contact records that associated account record and no.of child records should be decided from account record with custom field in account.

Best Answer chosen by bhupal reddy 7
bhupal reddy 7bhupal reddy 7
The below code will be helpful for such kind of scenario!!!

trigger AccountTrigger1 on Account (After insert) {
    List<Contact> Conlisttoupdate = new List<Contact>();
    Map<Id,Account> MapofAccount = new Map<id,Account>();
    if(trigger.isInsert && trigger.isAfter){
        for(Account Acc:Trigger.new){
            if(Acc.Total_No_of_Contacts__c != Null){
                MapofAccount.put(Acc.Id, Acc); 
            }
            for(Integer i = 0;i<MapofAccount.get(Acc.Id).Total_No_of_Contacts__c;i++){
                contact Con = new Contact();
                Con.AccountId = Acc.Id;
                Con.LastName = Acc.Name + i;
                Conlisttoupdate.add(Con);
            }
        }
        If(!Conlisttoupdate.isEmpty()){
            insert Conlisttoupdate;
        }
    }  
}


 Thanks,
Bhupal Kanakanti.