function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
PRADEEP YADAV 5PRADEEP YADAV 5 

Save the previous details of the opportunity records to BackUp record whenever any changes are being made to any opportunity record

trigger OpportunityBackup on Opportunity (after update) 
{

      List<My_Backup__c> lstToInsrt = new List<My_Backup__c>();      
    for(Opportunity op1 : Trigger.new)
    {
         if(trigger.oldMap.get(op1.Id).Name !=op1.Name)
         {
             My_Backup__c backup = new My_Backup__c();
             backup.Name = trigger.oldMap.get(op1.AccountId).Name;
             lstToInsrt.add(backup);
         }
    }
    if(lstToInsrt.size()>0)
    {
        update lstToInsrt;
    }
    
}
PRADEEP YADAV 5PRADEEP YADAV 5
OpportunityBackup: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.OpportunityBackup: line 10, column 1
Error 
 
Maharajan CMaharajan C
Hi pradeep,

Try the below code:
 
trigger OpportunityBackup on Opportunity (after update) 
{
    Map<Id,Account> oppMap = new Map<Id,Account>([Select Id,Name from Account where Id IN (Select AccountId from Opportunity where Id IN: trigger.oldMap.keyset())]);      
    List<My_Backup__c> lstToInsrt = new List<My_Backup__c>();      
    for(Opportunity op1 : Trigger.new)
    {
         if(trigger.oldMap.get(op1.Id).Name !=op1.Name)
         {
             My_Backup__c backup = new My_Backup__c();
             backup.Name = oppMap.get(op1.AccountId).Name;
             lstToInsrt.add(backup);
         }
    }
    if(lstToInsrt.size()>0)
    {
        insert lstToInsrt;
    }
    
}



Thanks,
Maharajan.C 
PRADEEP YADAV 5PRADEEP YADAV 5
Thanks Maharajan