Here's an Apex Trigger that automatically creates a related Opportunity whenever an Account is created.
trigger CreateOpportunityOnAccountInsert on Account (after insert) {
List<Opportunity> opportunitiesToInsert = new List<Opportunity>();
for (Account acc : Trigger.new) {
// Create an Opportunity for each new Account
Opportunity opp = new Opportunity();
opp.Name = acc.Name + ' Opportunity'; // Opportunity name based on Account Name
opp.AccountId = acc.Id;
opp.StageName = 'Prospecting'; // Default stage for the Opportunity
opp.CloseDate = Date.today().addMonths(1); // Default Close Date 1 month from today
opportunitiesToInsert.add(opp);
}
// Perform bulk insert of Opportunities
if (!opportunitiesToInsert.isEmpty()) {
insert opportunitiesToInsert;
}
}
Explanation of the Code
Trigger Event:
- The trigger runs on the
after insert
event to ensure the Account is fully created before creating the Opportunity and linking it to the Account.
- The trigger runs on the
Logic:
- For each new Account created, a new Opportunity is created with the following default values:
- Name: The Opportunity is named after the Account with the suffix " Opportunity."
- StageName: Set to 'Prospecting' (default).
- CloseDate: Set to one month from the current date.
- AccountId: Links the Opportunity to the newly created Account.
- For each new Account created, a new Opportunity is created with the following default values:
Bulk Processing:
- The trigger collects all the Opportunity records in a list and performs a bulk insert to ensure efficient processing.