To create a trigger that generates a number of Contacts equal to the value entered in the Number of Locations field on the Account object, follow the implementation steps below. Each Contact will be linked to the Account, and you can customize their attributes (e.g., name).
trigger CreateContactsBasedOnLocations on Account (after insert) {
List<Contact> contactsToInsert = new List<Contact>();
for (Account acc : Trigger.new) {
// Check if Number_of_Locations__c is populated and greater than zero
if (acc.Number_of_Locations__c != null && acc.Number_of_Locations__c > 0) {
Integer numberOfContacts = acc.Number_of_Locations__c.intValue();
for (Integer i = 1; i <= numberOfContacts; i++) {
// Create a Contact for each location
contactsToInsert.add(new Contact(
FirstName = 'Location',
LastName = acc.Name + ' ' + i, // Use Account Name + index for uniqueness
AccountId = acc.Id // Link Contact to the Account
));
}
}
}
// Insert all Contacts in bulk
if (!contactsToInsert.isEmpty()) {
insert contactsToInsert;
}
}
Explanation of the Code
Trigger Event:
- Runs on the
after insert
event since we need theAccountId
for associating Contacts with the Account.
- Runs on the
Logic:
- The trigger checks if the custom field Number_of_Locations__c (assumed to be a custom field) has a value and if it's greater than zero.
- It then loops based on the value in Number_of_Locations__c, creating that many Contact records.
Bulk Processing:
- Ensures efficient handling by collecting all Contacts in a
List<Contact>
and inserting them in bulk.
- Ensures efficient handling by collecting all Contacts in a
Contact Fields:
- LastName: Combines the Account name with an index (e.g.,
AccountName 1
,AccountName 2
) to ensure uniqueness.