+ Start a Discussion
Deepak Pandey 13Deepak Pandey 13 

trigger deleting record will save another custom object

sir i have a question that if any record has been deleted than deleted record will be save in another custom object. using trigger. anybody help me?. 
Best Answer chosen by Deepak Pandey 13
Deepak Pandey 13Deepak Pandey 13
trigger createBackup on Account (after delete) 
{
 if(trigger.isDelete && trigger.isAfter)
 {
  List<My_Backup__c> lstToInsrt = new List<My_Backup__c>();  
  for(Account deletedAcc : trigger.old)
  {
   system.debug('deletedAcc '+deletedAcc );
   My_Backup__c backup = new My_Backup__c();
   backup.Name = deletedAcc.name;
   lstToInsrt.add(backup);
   system.debug('backup '+backup);
  }
  if(lstToInsrt.size()>0)
  {
   insert lstToInsrt;
   system.debug('list'+lstToInsrt);
  }
 }
}

All Answers

James LoghryJames Loghry
Deepak, there are several "maams" here too that help quite a bit, so please keep them in mind as well.

Generally speaking, you would need to create a trigger that fires on before (or after) delete.  This will fire when a record is deleted, with the exception being cascade deletes.

Cascade deletes happen when a parent is deleted and any detail records in a master / detail relationship are deleted as a result.  In that particular case, you would add your logic for the master record and any children detail records as well.

In your before delete trigger, you would construct a list of new custom object records and then insert them after the list is generated.
Deepak Pandey 13Deepak Pandey 13
trigger createBackup on Account (after delete) 
{
 if(trigger.isDelete && trigger.isAfter)
 {
  List<My_Backup__c> lstToInsrt = new List<My_Backup__c>();  
  for(Account deletedAcc : trigger.old)
  {
   system.debug('deletedAcc '+deletedAcc );
   My_Backup__c backup = new My_Backup__c();
   backup.Name = deletedAcc.name;
   lstToInsrt.add(backup);
   system.debug('backup '+backup);
  }
  if(lstToInsrt.size()>0)
  {
   insert lstToInsrt;
   system.debug('list'+lstToInsrt);
  }
 }
}
This was selected as the best answer