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
Dheeraj ShoppeDheeraj Shoppe 

Exception : DML statement cannot operate on trigger.new or trigger.old

I'm trying to delete leads after converting to contacts, but getting the exception 'DML statement cannot operate on trigger.new or trigger.old'.
Below is the code where I'm facing issue at delete leadListToDelete. Can any explain this? 
trigger LeadToContact on Lead (before insert, before update, after insert, after update) {   
    //Map<Id, Lead> leadIds = new Map<Id, Lead>();
    List<Lead> leadList = new List<Lead>();
    List<Lead> leadListToDelete = new List<Lead>();
    
    if(trigger.isBefore){
    	for (Lead l : trigger.New){
        	if(l.Status == 'Open - Not Contacted'){
            	if(l.Email_Domain__c != null){
                	leadList.add(l);
                 	System.debug('New leads having Email domain ### ' + leadList);
            	}
        	}
    	}
    
    	List<Account> accList = [select id, Email_Domain__c from Account where Email_Domain__c LIKE '%com'];        
    	List<Contact> contactList = new List<Contact>(); 	
   
    	for(Account acc :accList){
        	for(Lead lead : leadList)
            	if(acc.Email_Domain__c == lead.Email_Domain__c){
                	Contact c = new Contact(LastName = lead.LastName, AccountId = acc.Id);
                	contactList.add(c);
                    System.debug('Contacts to be created : ' + contactList);
                	leadListToDelete.add(lead);
                    System.debug('Delete Leads ## ' + leadListToDelete);
            	}
    	}
    
    	insert contactList;
    	delete leadListToDelete;
    	}
 
}
Thanks in Advance!
Best Answer chosen by Dheeraj Shoppe
Dario BakDario Bak
You cannot operate on records from the trigger context. You can take those same records and perform DML on them if you simply change the reference.
 
List<Event> nonTriggerEvents = new List<Event>(); 
for (Event triggerEvent : trigger.new) { 
   nonTriggerEvents.add(new Event(Id = triggerEvent.Id)); 
} 
delete nonTriggerEvents;


 

All Answers

Naval Sharma4Naval Sharma4
Hi Dheeraj,

Instead of doing DML in before trigger you can do this in after trigger.

Thanks,
Naval
Dario BakDario Bak
You cannot operate on records from the trigger context. You can take those same records and perform DML on them if you simply change the reference.
 
List<Event> nonTriggerEvents = new List<Event>(); 
for (Event triggerEvent : trigger.new) { 
   nonTriggerEvents.add(new Event(Id = triggerEvent.Id)); 
} 
delete nonTriggerEvents;


 
This was selected as the best answer