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
Supraja KallakuriSupraja Kallakuri 

System.SObjectException: DML statment cannot operate on trigger.new or trigger.old

When I try to test this code, it throws an error saying ' System.SObjectException: DML statment cannot operate on trigger.new or trigger.old'

Any ideas why?

Trigger MasterRFSTrigger on Account(before insert, before update){
 Set<String> chaincodes = New Set<String>();
    List<Account> Accslist = New List<Account>();
     
    if(trigger.isinsert){
        for (Account a :trigger.new){
            if (a.Other_Chain__c!=null){
                chaincodes.add(a.Other_Chain__c);
  
            }
        }
    }else if(trigger.isupdate){       
            for(Account a : trigger.new){
                String oldchaincode = trigger.oldmap.get(a.id).Chaincode__c;
                String newchaincode = a.Chaincode__c;
                if(newchaincode != oldchaincode){
                    chaincodes.add(newchaincode);
                }
            }
        }
    Map<String, Chain__c> chainconfig = new Map<String, Chain__c>();
    List<Chain__c> chains = [SELECT Name, Chain_Name__c, Company__c FROM Chain__c WHERE Name in : chaincodes];
    for(Chain__c c : chains){
        chainconfig.put(c.Name, c);
    }
     
    for(Account a :trigger.new){
        Chain__c Chain =chainconfig.get(a.Chaincode__c);
        if(Chain != null){
            a.Chainname__c = Chain.Chain_Name__c;
            a.Company__c =Chain.Company__c;
        }Accslist.add(a);
        }
     Insert Accslist;
        
}
BalajiRanganathanBalajiRanganathan
Remove the DML statement at the end.
Insert Accslist; // remove this line.

Below will be the order of execution
Executes all before trigger (your code)
Saves the record to the database but doesn't commit yet (insert or update or delete. sfdc will do)
Executes all after triggers

check the order of execution of triggers

https://www.salesforce.com/us/developer/docs/apexcode/Content/apex_triggers_order_of_execution.htm