Skip to content

Instantly share code, notes, and snippets.

@ganmahmud
Last active November 23, 2018 09:48
Show Gist options
  • Save ganmahmud/ea29aa65049257ed69e74e84fc386df3 to your computer and use it in GitHub Desktop.
Save ganmahmud/ea29aa65049257ed69e74e84fc386df3 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 ( Bulk Query Optimized )
trigger AddRelatedRecord on Account(after insert, after update) {
List<Opportunity> oppList = new List<Opportunity>();
// Add an opportunity for each account if it doesn't already have one.
// Iterate over accounts that are in this trigger but that don't have opportunities.
for (Account a : [SELECT Id,Name FROM Account
WHERE Id IN :Trigger.New AND
Id NOT IN (SELECT AccountId FROM Opportunity)]) {
// Add a default opportunity for this account
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