To meet your requirements, we'll create an Apex Trigger on the Account object. This trigger will check the values of the Contact and Opportunity checkbox fields on the Account. If the Contact checkbox is checked, a related Contact will be created, and if the Opportunity checkbox is checked, an Opportunity will be created. The Opportunity will only be created if the Active picklist on the Account is set to "Yes."
trigger CreateRelatedRecordsOnAccountCreate on Account (after insert) {
List<Contact> contactsToInsert = new List<Contact>();
List<Opportunity> opportunitiesToInsert = new List<Opportunity>();
// Loop through all newly created Accounts
for (Account acc : Trigger.new) {
// Check if the Contact checkbox is selected
if (acc.Contact__c == true) { // Contact__c is the checkbox field on Account
Contact newContact = new Contact();
newContact.AccountId = acc.Id;
newContact.LastName = acc.Name + ' Contact'; // Set Contact LastName based on Account Name
newContact.Email = acc.Name + '@example.com'; // Sample email, customize as needed
contactsToInsert.add(newContact);
}
// Check if the Opportunity checkbox is selected and the Account is Active
if (acc.Opportunity__c == true && acc.Active__c == 'Yes') { // Opportunity__c and Active__c fields
Opportunity newOpportunity = new Opportunity();
newOpportunity.AccountId = acc.Id;
newOpportunity.Name = acc.Name + ' Opportunity'; // Set Opportunity Name based on Account Name
newOpportunity.StageName = 'Prospecting'; // Default Stage
newOpportunity.CloseDate = Date.today().addMonths(1); // Default Close Date 1 month from today
opportunitiesToInsert.add(newOpportunity);
}
}
// Insert the related Contacts if there are any
if (!contactsToInsert.isEmpty()) {
insert contactsToInsert;
}
// Insert the related Opportunities if there are any
if (!opportunitiesToInsert.isEmpty()) {
insert opportunitiesToInsert;
}
}
Explanation of the Code
Trigger Event:
- This trigger runs on the
after insert
event because we want to create the Contact and Opportunity records after the Account record has been created.
- This trigger runs on the
Logic:
- For each new Account, the trigger checks:
- If the Contact checkbox (
Contact__c
) is checked, a Contact is created and linked to the Account. - If the Opportunity checkbox (
Opportunity__c
) is checked and the Active picklist field (Active__c
) is set to "Yes", an Opportunity is created and linked to the Account.
- If the Contact checkbox (
- The Opportunity will only be created if the Active picklist is set to "Yes" on the Account.
- For each new Account, the trigger checks:
Bulk Processing:
- The trigger is designed to handle bulk processing, meaning if multiple Account records are inserted, the corresponding Contact and Opportunity records are created in bulk.
Default Values:
- The Contact record will have a default
LastName
based on the Account name and a sample email. - The Opportunity will have a default Stage of "Prospecting" and a CloseDate set to one month from today.