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
Abhishek AS 3Abhishek AS 3 

trigger to create contacts based on the number in number of contacts field on account

write trigger for:
Creates the number of contacts which are equal to the number which we will enter in the Number of Locations field on the Account Object.
Create Custom field called “Number of Locations” on the Account Object (Data Type=Number). can anyone provide code for this requirement
 
AnkaiahAnkaiah (Salesforce Developers) 
Hi Abhishek,

try with below code and modify the field api names as per your org.
trigger ContactsCreation on Account (after insert) {
    
    List<Contact> conlist = new List<contact>();
    
    for(account acc:trigger.new){
        
        if(acc.Number_of_Locations__c !=Null){
            
            for(integer i=1;i<=acc.Number_of_Locations__c;i++){
                
                contact con = new contact();
                con.LastName = acc.Name+i;
                con.phone = acc.phone;
                con.AccountId = acc.id;
                conlist.add(con);
            }
            
        }
    }
    
    insert conlist;

}
If this helps, Please mark it as best answer.

Thanks!!
 
CharuDuttCharuDutt
Hii Abhishek
Try Below Code
trigger HelloWorldTrigger on Account (after insert){
    list<Contact> lstNewContacts = new list<Contact>();
    for(Account Acc : trigger.new){
        if(Acc.Number_Of_Locations__c != null && Acc.Number_Of_Locations__c != 0){
            for(integer i=0;i< Acc.Number_Of_Locations__c;i++){
                Contact Con = new Contact();
                COn.LastName = 'Acc.Name';
                COn.AccountId = Acc.Id;
                //fill all Required Fields
                lstNewContacts.add(Con);
    
            }
        }
    }
    if(lstNewContacts.size()>0){
    insert lstNewContacts;
    }
}
Please Mark It As Best Asnwer If It Helps
Thank You! 
Abhishek AS 3Abhishek AS 3
Thank you for your response. Can u avoid two for loops and use map instead. Is there a way to do it.
Lukesh KarmoreLukesh Karmore
Hi Abhishek,

try with below code and modify the field api names as per your org.
 
trigger ContactsCreation on Account (after insert) {
    
     decimal number=0;
    for(account acc:trigger.new){
       if(acc.Number_of_Locations__c !=Null){
       number=acc.Number_of_Locations__c;
          }
       }
      List<Contact> conlist = new List<contact>();
          for(integer i=1;i<=number;i++){
                
                contact con = new contact();
                con.LastName = acc.Name+i;
                con.phone = acc.phone;
                con.AccountId = acc.id;
                conlist.add(con);
            }
     insert conlist;

}
Please Mark It As Best Asnwer If It Helps
Thank You!