Development questions
When an Account is restored from the Recycle Bin (after undelete), append " - Restored" to its Name and send a notification to the System Admin.
In after undelete, Trigger.new is read-only, so create new SObject instances with the Id (or re-query) and update them. Then notify an admin.
apex
trigger AccountTrigger on Account (after undelete) {
List<Account> toUpdate = new List<Account>();
for (Account a : Trigger.new) toUpdate.add(new Account(Id = a.Id, Name = a.Name + ' - Restored'));
update toUpdate;
User admin = [SELECT Email FROM User WHERE Profile.Name = 'System Administrator' AND IsActive = true LIMIT 1];
Messaging.SingleEmailMessage m = new Messaging.SingleEmailMessage();
m.setToAddresses(new String[]{ admin.Email });
m.setSubject('Accounts restored');
m.setPlainTextBody(toUpdate.size() + ' Account(s) restored from the Recycle Bin.');
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{ m });
}
Use a custom notification or Chatter post if email isn't preferred.
apex-triggertriggercodingscenarioundelete
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?