To create a Contact automatically whenever a new Account is created, you can write an Apex Trigger in Salesforce. Here's how to implement this functionality:
trigger CreateContactOnAccountInsert on Account (after insert) {
List<Contact> contactsToInsert = new List<Contact>();
for (Account acc : Trigger.new) {
// Create a Contact record associated with the Account
contactsToInsert.add(new Contact(
FirstName = 'Default',
LastName = acc.Name, // Using Account Name as the Contact's Last Name
AccountId = acc.Id // Linking Contact to the Account
));
}
// Insert all new Contacts in bulk
if (!contactsToInsert.isEmpty()) {
insert contactsToInsert;
}
}
Explanation of the Code
Trigger Event:
- The trigger runs on the
after insert
event because we need theAccountId
(generated only after the Account record is saved) to link the Contact to the Account.
- The trigger runs on the
Logic:
- For every Account in the
Trigger.new
list, a newContact
is created with:- A default
FirstName
(you can customize this). LastName
as the Account’sName
.AccountId
to associate the Contact with the Account.
- A default
- For every Account in the
Bulk Handling:
- All new Contact records are stored in a
List<Contact>
and inserted in bulk to ensure efficient processing in case of bulk Account creation.