Here’s an Apex Trigger that creates a Contact for an Account when the Industry is set to Banking
. The Contact's LastName will be the Account Name, and the Contact's Phone will be the Account's Phone.
trigger CreateContactForBankingAccount on Account (after insert) {
List<Contact> contactsToInsert = new List<Contact>();
for (Account acc : Trigger.new) {
// Check if the Industry is Banking
if (acc.Industry == 'Banking') {
// Create a Contact associated with the Account
contactsToInsert.add(new Contact(
LastName = acc.Name, // LastName as Account Name
Phone = acc.Phone, // Contact Phone as Account Phone
AccountId = acc.Id // Associate Contact with Account
));
}
}
// Insert all Contacts in bulk
if (!contactsToInsert.isEmpty()) {
insert contactsToInsert;
}
}
Explanation of the Trigger
Trigger Event:
- The trigger runs on the
after insert
event because theAccountId
is needed to associate the Contact with the Account.
- The trigger runs on the
Condition:
- The trigger checks if the
Industry
field on the Account is set toBanking
.
- The trigger checks if the
Contact Fields:
- LastName: Set to the Account Name.
- Phone: Set to the Account Phone.
- AccountId: Links the Contact to the newly created Account.
Bulk Processing:
- The code is bulkified by adding Contact records to a
List<Contact>
and inserting them in bulk.