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
srikanth j 24srikanth j 24 

Salesforce Account and Contact Trigger

Hi guys,
if i insert or update 1 account i need to create 5 contacts to that account Using Trigger how can approach this one 
can anyone help me out if possible send me code 
Advance Thanks
Best Answer chosen by srikanth j 24
Medhya MahajanMedhya Mahajan
Hi Srikanth, 

If you are looking for a simple logic behind it, here's one I have written for you.
You can add any changes that you require according to your will.
 
trigger InsertContacts on Account (after insert, after update ) {

List<Contact> contactList = new List<Contact>();

for (Account acc: trigger.new){
        for(Integer i = 0 ; i< 5 ; i++){
            String firstName = 'New';
            String lastName = 'Contact' + i;
            contactList.add(new Contact (FirstName = firstName, LastName = lastName, AccountId = acc.Id));
        } 

     if( !contactList.isEmpty()){
         insert contactList; 
        }   
    }
}

Create this trigger, update an account and you will see 5 contacts in the contact Related List of the account.

Mark solved if this answers your question.

Regards
Medhya Mahajan

All Answers

UC InnovationUC Innovation
Hi srikanth,

Just need some more info from you. What exactly should I populate the fields of the contacts with? Names,...etc.

Thanks,

AM
srikanth j 24srikanth j 24
Yes Contacts with Names That's it
Medhya MahajanMedhya Mahajan
Hi Srikanth, 

If you are looking for a simple logic behind it, here's one I have written for you.
You can add any changes that you require according to your will.
 
trigger InsertContacts on Account (after insert, after update ) {

List<Contact> contactList = new List<Contact>();

for (Account acc: trigger.new){
        for(Integer i = 0 ; i< 5 ; i++){
            String firstName = 'New';
            String lastName = 'Contact' + i;
            contactList.add(new Contact (FirstName = firstName, LastName = lastName, AccountId = acc.Id));
        } 

     if( !contactList.isEmpty()){
         insert contactList; 
        }   
    }
}

Create this trigger, update an account and you will see 5 contacts in the contact Related List of the account.

Mark solved if this answers your question.

Regards
Medhya Mahajan
This was selected as the best answer
srikanth j 24srikanth j 24
Thanks Medhya.