Skip to content

Instantly share code, notes, and snippets.

@WPAcademic
Last active January 20, 2023 20:41
Show Gist options
  • Save WPAcademic/44f624e4419f991716330ea94c77c46a to your computer and use it in GitHub Desktop.
Save WPAcademic/44f624e4419f991716330ea94c77c46a to your computer and use it in GitHub Desktop.
Trigger Apex Bulk DML on Trigger
/**
* The trigger fires after accounts are inserted or updated. 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>();
// this will be determined by the operation type
List<Account> toProcess = null;
switch on Trigger.operationType {
when AFTER_INSERT {
toProcess = Trigger.New;
}
when AFTER_UPDATE
// SELECT account that don't already have a related opportunity
toProcess = [Select Id, Name FROM Account WHERE Id IN :trigger.New AND Id NOT IN (Select AccountId FROM OPPORTUNITY WHERE AccountId IN :Trigger.NEW)];
}
}
for (Account a : toProcess) {
oppList.add(new Opportunity(Name = a.name + ' Opportunity', 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