You need to sign in to do that
Don't have an account?
Dheeraj 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?
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!
All Answers
Instead of doing DML in before trigger you can do this in after trigger.
Thanks,
Naval