Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

dml statement cannot operate on trigger.new or trigger.old

Asked by Charles Parr May 24, 2024 3.2K views 3 answers
Share

About this question

 I am currently engaged in a particular task that is related to a Salesforce project in which I need to update some records based on the specific criteria during an after-update trigger. Explain to me how cannot I directly modify records by using the DML statement on “trigger.new” or “trigger.old”? 

Your answer

3 Answers

Canconse Latest answer

Answered on Mar 13, 2025

The reason is because the after-update trigger was fired after the record was updated. Trying to update the record in this trigger would create an infinite loop geometry dash lite, because each update would fire the trigger.

Was this helpful?

Ranjana Admin JanBask Expert

Answered on Mar 4, 2025

If you're seeing the error "DML statement cannot operate on Trigger.new or Trigger.old" in Salesforce, it means you're trying to perform a DML operation (Insert, Update, Delete) directly on these collections inside a trigger. Here’s why this happens and how to fix it:

1. Why Does This Error Occur?

Trigger.new and Trigger.old are read-only in after triggers.

You cannot use insert, update, or delete directly on these collections.

Example of incorrect code:

trigger AccountTrigger on Account (after update) {
    for (Account acc : Trigger.new) {
        acc.Name = 'Updated Name';  // ❌ This will cause an error
        update acc;  // ❌ DML operation not allowed on Trigger.new
    }
}

2. How to Fix It?

✅ Use a separate list to store records and perform DML outside the loop.

Correct way:

trigger AccountTrigger on Account (after update) {
    List accList = new List();
    for (Account acc : Trigger.new) {
        Account updatedAcc = new Account(Id = acc.Id, Name = 'Updated Name');
        accList.add(updatedAcc);
    }
    if (!accList.isEmpty()) {
        update accList;  // ✅ Allowed because it's outside Trigger.new
    }
}

3. Best Practices to Avoid This Issue

✔ Use before triggers if you need to modify Trigger.new directly.

✔ In after triggers, use a separate list to perform DML operations.

✔ Avoid DML operations inside loops to improve performance.


Was this helpful?

More Salesforce discussions