AFTER UNDELETE:
This event runs the block of code after the deleted data is undeleted.
Operations such as validation can be performed under this event to prevent
wrong entry inside the database.
SYNTAX:
trigger triggerName on objectName (after undelete) {
// Block of code
}
SCENARIO:
We have the requirement that whenever a deleted account
is restored we need to set one of the
existing Account as ” Parent account” on the restored account.
APEX TRIGGER:
trigger AccountMainTrigger on Account (after undelete) { //
Specifying the event.
createContactClass obj=new
createContactClass(); // Creating
the instance of the class.
if(trigger.isafter &&
trigger.isundelete) // Using
context variable.
{
obj.method1(); // Calling apex class method.
}
}
APEX CLASS:
public class createContactClass {
public void method1(){
Account obj=[SELECT id from Account
where name='Test record creation' Limit 1]; // As default account need to be set as parent account on undeleted account
hence using the above account with name 'Test record creation’.
List<Account> accObjList=new
List<Account>();
accObjList=[SELECT id,ParentId from
Account where id in:trigger.newmap.keyset()];
for(Account acc:accObjList){
if(acc.ParentId==null){
acc.ParentId=obj.id; // Setting the parent account on undeleted account.
}
}
if(accObjList.size() > 0){ // Checking if the list has
records.
update accObjList; // Updating records.
}
}
}
Let us try to delete the below account,
Now to restore the deleted Account click on “Undo” as shown
in the above image, it will get restored with parent Account what we have set
using apex class. Please refer below images.
No comments:
Post a Comment