• AMAN RANA
  • NEWBIE
  • 0 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 1
    Questions
  • 1
    Replies
I have created a Custom field called “Number of Locations” on the Account Object (Data Type=Number)
Object : Account
Trigger: After Insert

This is my code:

trigger ContactsCreation on Account (after insert) {
list<contact> listContact = new list<contact>();
map<id,decimal> mapAcc = new map<id,decimal>();
  for(Account acc:trigger.new){
      mapAcc.put(acc.id,acc.NumberofLocations__c);
     }
        if(mapAcc.size()>0 && mapAcc!=null){
            for(Id accId:mapAcc.keyset()){
               for(integer i=0;i<mapAcc.get(accId);i++){
                 contact newContact=new contact();
                 newContact.accountid=accId;
                 newContact.lastname='contact'+i;
                 listContact.add(newContact);
                 }
              }
         }
if(listContact.size()>0 && listContact!=null)
insert listContact;

Can someone please explain the logic behind the no of creation of contact records based on location field.
Sample example: I have given account name,no of locations=2 in account object, then after two contacts record got created with lastname as contact0,contact1.
Why multiple contacts are creating as per the above logic?
 
  • March 25, 2021
  • Like
  • 0