Skip to content

Instantly share code, notes, and snippets.

  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save AmbreJuryeaAmole/f5a11142c9fb719edba14623784cd153 to your computer and use it in GitHub Desktop.
Trigger Good Example no try/catch
trigger CaseTrigger on Case (after insert) {
system.debug('***CaseTrigger begin');
// In this example trigger we are simply wanting to flag at the Account level
// that the Account has a Case linked to it, which is a lookup field on Case
// so we wouldn't be able to do a rollup count.
// In reality we would also want to track deletes of Cases but that is skipped
// for demonstration purposes.
// bulk map of accounts that we need to update
map<Id, Account> accountsForUpdateMap = new map<Id, Account>();
// find accounts to update
for(Case c : trigger.new){
// if this case is linked to an account and we've not already tagged this account
if(c.AccountId != null && !accountsForUpdate.containsKey(c.AccountId))
// add this account to the map
accountsForUpdate.put(c.AccountId, new Account(Id = c.AccountId, HasACase__c = true));
}
// check to see if we need to perform DML
if(!accountsForUpdate.isEmpty())
// let's do the DML
update accountsForUpdate.values();
// If we get this far in code, the DML finished properly
system.debug('Success');
// If anything were to go wrong in the above DML, since we do NOT have a try/catch then the server
// will automatically rollback the changes (In this instance the Cases in this trigger
// would not be inserted into the database since the account DML update failed. This is usually
// desired so that the Account data is accurate.)
// A complex error would show on the calling page or calling code that fired this trigger
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment