0

This question already has an answer here:

I want to delete record from custom object where name = new. I wrote simple apex trigger to delete this records however I am getting below error when execute.

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

Apex Trigger

trigger DuplicateTemp on Temp__c(before update) {
    List<Temp__c> tempToDelete = new List<Temp__c>();

    for(Temp__c temp: Trigger.New){
        If (temp.Name == 'New'){

            tempToDelete.add(temp);
        }
    }
         Database.delete(tempToDelete); 
}

marked as duplicate by Adrian Larson Jun 8 '17 at 16:57

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

you can't do dml on objects, that are in trigger at current transaction. To achieve it, you can collect ids of records, that you want to delete and then delete them, and do it on after update:

trigger DuplicateTemp on Temp__c(after update) {
    List<Id> tempToDeleteIds = new List<Id>();
    for(Temp__c temp: Trigger.New){
        If (temp.Name == 'New'){
            tempToDeleteIds.add(temp.Id);
        }
    }
    Database.delete(tempToDeleteIds); 
}

Not the answer you're looking for? Browse other questions tagged or ask your own question.