Skip to content

Instantly share code, notes, and snippets.

@ganmahmud
Last active November 23, 2018 09:48
Show Gist options
  • Save ganmahmud/8189ca1f94af0f1556cb870b71c57980 to your computer and use it in GitHub Desktop.
Save ganmahmud/8189ca1f94af0f1556cb870b71c57980 to your computer and use it in GitHub Desktop.
The trigger adds a default opportunity for every account that doesn’t already have an opportunity
trigger AddRelatedRecord on Account(after insert, after update) {
List<Opportunity> oppList = new List<Opportunity>();
// Get the related opportunities for the accounts in this trigger
Map<Id,Account> acctsWithOpps = new Map<Id,Account>(
[SELECT Id,(SELECT Id FROM Opportunities) FROM Account WHERE Id IN :Trigger.New]);
// Add an opportunity for each account if it doesn't already have one.
// Iterate through each account.
for(Account a : Trigger.New) {
System.debug('acctsWithOpps.get(a.Id).Opportunities.size()=' + acctsWithOpps.get(a.Id).Opportunities.size());
// Check if the account already has a related opportunity.
if (acctsWithOpps.get(a.Id).Opportunities.size() == 0) {
// If it doesn't, add a default opportunity
oppList.add(new Opportunity(Name=a.Name + ' Opportunity',
StageName='Prospecting',
CloseDate=System.today().addMonths(1),
AccountId=a.Id));
}
}
if (oppList.size() > 0) {
insert oppList;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment