[SalesForce] Creating contacts that depend on an account field value

Assume I have a number field in an Account object. When I insert a new record with a number field of value that equals 2. Two contact should be created. When I insert a new record with a number field with a value of 5, then 5 contacts should be created.

How can I archive this in a trigger?

Best Answer

Try below code.

trigger newContactTrigger on Account (before insert) {
   Integer numberOfContacts=0;
   // getting conunt
   for(account a : trigger.new){
      numberOfContacts = (Integer)a.Number_of_contacts__c;
   }
   List<contact> listOfContactToInsert = new List<contact>();
   // creating contact records
   for(integer i = 1; i<=numberOfContacts;i++){
      contact c =  new contact();
      c.LastName = 'Test'+i;
      listOfContactToInsert.add(c);
   }
   insert listOfContactToInsert;
}

First you have to create the trigger on account object and lets say number_of_contacts__c is the cont of contact records you want to create. Now, your new account record will be in trigger.new as we are using insert operation. Get number of contact records from trigger.new as shown in code using for loop. Once you have number of contacts to create, create contact record in for loop iterating till number of contacts you want to craete and add that record in a list. then use insert DML operation to insert your new contact list.

Related Topic