Create a custom field called “Number of Locations” (its API name: NumberofLocations__c
) on the Account Object (Data Type=Number).Create multiple contacts by Account depending on the NumberofLocations__c field.
Trigger
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;
}
Trigger.new
. It avoids using the same for loop twice and the use of theMap
.if
statements should be reversed, at the moment if the list is null they will attempt to dereference a null list to callsize()
before checking whether the list is null, throwing an exception.