Here's an Apex Trigger that creates a related Contact automatically whenever an Account is created.
trigger CreateContactOnAccountInsert on Account (after insert) {
List<Contact> contactsToInsert = new List<Contact>();
for (Account acc : Trigger.new) {
// Create a Contact for each new Account
Contact con = new Contact();
con.FirstName = 'Default';
con.LastName = acc.Name; // Use Account Name as LastName
con.AccountId = acc.Id;
contactsToInsert.add(con);
}
// Perform bulk insert of Contacts
if (!contactsToInsert.isEmpty()) {
insert contactsToInsert;
}
}
Explanation of the Code
Trigger Event:
- Runs on the
after insert
event since the Account ID is needed to associate the Contact with its parent Account.
- Runs on the
Logic:
- Loops through all the newly created Account records in
Trigger.new
. - Creates a Contact record for each Account with:
- A default FirstName (
Default
in this case). - The Account Name as the LastName.
- Links the Contact to the Account using the AccountId field.
- A default FirstName (
- Loops through all the newly created Account records in
Bulk Processing:
- Collects all Contact records in a list and performs a single bulk insert, which is more efficient and avoids governor limits.
@isTest
private class CreateContactOnAccountInsertTest {
@isTest
static void testCreateContactOnAccountInsert() {
// Create a list of Accounts for bulk testing
List<Account> accounts = new List<Account>{
new Account(Name = 'Account 1'),
new Account(Name = 'Account 2'),
new Account(Name = 'Account 3')
};
// Insert the Accounts
insert accounts;
// Verify that Contacts are created
List<Contact> createdContacts = [SELECT FirstName, LastName, AccountId FROM Contact WHERE AccountId IN :accounts];
System.assertEquals(3, createdContacts.size(), 'Three Contacts should be created for three Accounts');
// Verify Contact details for the first Account
Contact contact1 = [SELECT FirstName, LastName FROM Contact WHERE AccountId = :accounts[0].Id];
System.assertEquals('Default', contact1.FirstName, 'Contact FirstName should be Default');
System.assertEquals('Account 1', contact1.LastName, 'Contact LastName should match Account Name');
}
}