[SalesForce] Unable to delete the current record

I am written one trigger as below it processing certain condition has been stratified then delete the current record.But I am Unable to delete the current record.

Code:

Trigger OrderDelete on Company__c (AFTER INSERT,AFTER UPDATE){
 LIST<Company__c> deletecom = NEW LIST<Company__c>();
    FOR(Company__c com : Trigger.new)
    {
        IF((com.Delete__c == TRUE)&&(com.Order_Source_Code__c == 'DUM'))
            deletecom.add(com);                            
    }
    IF(deletecom.SIZE() != 0)
        DELETE deletecom;
} 

It throw an exception why I don't no.

EXCEPTION :

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger OrderDelete caused an unexpected exception, contact your administrator: OrderDelete: execution of AfterInsert caused by: System.SObjectException: DML statment cannot operate on trigger.new or trigger.old: Trigger.OrderDelete: line 21, column 1

Some one please help me …..

Best Answer

I expect you're receiving this error (including spelling mistake, well done SF):

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

That's because the record you are trying to delete is in the Trigger.new collection. You would need to re-query the records first:

List<Company__c> companies = [Select Id From Company__c Where Id IN :Trigger.new];

Then, loop companies instead of Trigger.new. The error message is self explanatory.

Related Topic