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?

  • 3
    Hi Raja, please take a moment to visit the help center, scroll through the tour, and read How to Ask. What have you tried so far? Where are you stuck? In general, we expect you to make a good faith effort before helping out. Right now, your post can basically be paraphrased as "please do my work for me". Please edit it to be specific about your attempts so far and any errors you face. – Adrian Larson May 6 '17 at 13:54

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;
   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.

| improve this answer | |
  • 1
    maybe you would like to explain your code so the user who asked will learn, rather than copy paste it and than ask for someone else to provide more code for future questions. How to Answer – glls May 6 '17 at 19:03
  • @glls Explained the code. – Muzammil Bajaria May 6 '17 at 19:20
  • Awesome! appreciate the effort put into this! – glls May 6 '17 at 19:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.