Trigger
trigger ContactTrigger on Contact (after insert) {
if (Trigger.isAfter && Trigger.isInsert) {
ContactTriggerHandler.createAccountForContacts(Trigger.new);
}
}
Apex Class
public class ContactTriggerHandler {
public static void createAccountForContacts(List<Contact> newContacts) {
// List to hold Account records that need to be created
List<Account> accountsToInsert = new List<Account>();
// Map to store the relationship between each Contact and its corresponding Account
Map<Id, Account> contactToAccountMap = new Map<Id, Account>();
// Loop through each inserted Contact record
for (Contact con : newContacts) {
// Create a new Account with the same name as the Contact's LastName
Account newAccount = new Account();
newAccount.Name = con.LastName; // You can use any field for the Account Name
// Add the Account to the list to be inserted
accountsToInsert.add(newAccount);
// Store the mapping of ContactId to Account (to link them later)
contactToAccountMap.put(con.Id, newAccount);
}
// Insert the Accounts
if (!accountsToInsert.isEmpty()) {
insert accountsToInsert;
}
// Now that the Accounts are inserted, we can update the Contacts to link them to the correct Account
List<Contact> contactsToUpdate = new List<Contact>();
// Loop through the newContacts again to associate Account with Contact
for (Contact con : newContacts) {
// Retrieve the corresponding Account from the map (the Account was inserted already)
Account acc = contactToAccountMap.get(con.Id);
// Create a new Contact record to update its AccountId
Contact updatedContact = new Contact(Id = con.Id); // Specify the Id to identify the record
updatedContact.AccountId = acc.Id;
// Add the updated Contact to the list
contactsToUpdate.add(updatedContact);
}
// Update the Contacts with the new AccountId
if (!contactsToUpdate.isEmpty()) {
update contactsToUpdate;
}
}
}