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

296    Asked by CharlesParr in Salesforce , Asked on May 24, 2024

 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”? 

Answered by Deepak Mistry

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

Answer:- In the context of Salesforce, DML (data manipulation language) statements such as insert, update, delete, and undelete cannot be directly applied to the “trigger.new” or “trigger.old” within an after trigger context. This limitation exists here because these trigger context variables represent only a collection of the records and Salesforce enforces this to prevent recursive triggers and maintain data integrity.

Instead of it you can use a separate list for holding the records which you want to update, and then perform the DML operation on this list outside of the trigger context. Here is an example given:-

Trigger AccountTrigger on Account (after update) {
    List accountsToUpdate = new List();
    // Iterate through Trigger.new to find records to update
    For (Account newAccount : Trigger.new) {
        // Check if the account type is ‘Customer’ and status is ‘Active’
        If (newAccount.Type == ‘Customer’ && newAccount.Status__c == ‘Active’) {
            // Modify the record – for example, change the priority to ‘High’
            newAccount.Priority__c = ‘High’;
            // Add the modified record to the separate list
            accountsToUpdate.add(newAccount);
        }
    }
    // Perform DML operation on the separate list of accounts to update
    If (!accountsToUpdate.isEmpty()) {
        Try {
            // Perform the update operation on the list of accounts
            Update accountsToUpdate;
        } catch (DmlException e) {
            // Handle any DML exceptions or errors
            For (Integer I = 0; I < e>

Here is the example given in java programming language:-

Import java.util.ArrayList;
Import java.util.List;
Public class AccountTrigger {
    Public static void main(String[] args) {
        List accountsToUpdate = new ArrayList<>();
        // Assuming Trigger.new is a list of updated Account objects
        List triggerNew = getTriggerNew(); // Method to simulate Trigger.new
        // Iterate through Trigger.new to find records to update
        For (Account newAccount : triggerNew) {
            // Check if the account type is ‘Customer’ and status is ‘Active’
            If (newAccount.getType().equals(“Customer”) && newAccount.getStatus().equals(“Active”)) {
                // Modify the record – for example, change the priority to ‘High’
                newAccount.setPriority(“High”);
                // Add the modified record to the separate list
                accountsToUpdate.add(newAccount);
            }
        }
        // Perform DML operation on the separate list of accounts to update
        If (!accountsToUpdate.isEmpty()) {
            // Assuming SalesforceService.updateAccounts() is a method to perform DML update
            Boolean updateSuccess = SalesforceService.updateAccounts(accountsToUpdate);
            If (updateSuccess) {
                System.out.println(“Accounts updated successfully!”);
            } else {
                System.out.println(“Failed to update accounts. Check logs for details.”);
            }
        }
    }
    // Method to simulate Trigger.new
    Private static List getTriggerNew() {
        List triggerNew = new ArrayList<>();
        // Add some Account objects to simulate Trigger.new
        Account account1 = new Account(“Account1”, “Customer”, “Active”);
        Account account2 = new Account(“Account2”, “Supplier”, “Inactive”);
        Account account3 = new Account(“Account3”, “Customer”, “Active”);
        triggerNew.add(account1);
        triggerNew.add(account2);
        triggerNew.add(account3);
        return triggerNew;
    }
}
Class Account {
    Private String name;
    Private String type;
    Private String status;
    Private String priority;
    Public Account(String name, String type, String status) {
        This.name = name;
        This.type = type;
        This.status = status;
        This.priority = “Low”; // Default priority
    }
    Public String getName() {
        Return name;
    }
    Public String getType() {
        Return type;
    }
    Public String getStatus() {
        Return status;
    }
    Public String getPriority() {
        Return priority;
    }
    Public void setPriority(String priority) {
        This.priority = priority;
    }
}
Class SalesforceService {
    Public static boolean updateAccounts(List accounts) {
        // Placeholder method to simulate DML update in Salesforce
        // In a real Salesforce environment, this would interact with Salesforce APIs
        // Here, we just print the updated accounts for demonstration purposes
        For (Account account : accounts) {
            System.out.println(“Updated Account: “ + account.getName() + “, Priority: “ + account.getPriority());
        }
        Return true; // Assuming update is successful for demonstration
    }
}
Here is the example given in python programming language:-
Class Account:
    Def __init__(self, name, type, status, priority=’Low’):
        Self.name = name
        Self.type = type
        Self.status = status
        Self.priority = priority
    Def __str__(self):
        Return f”Name: {self.name}, Type: {self.type}, Status: {self.status}, Priority: {self.priority}”
Class SalesforceService:
    @staticmethod
    Def update_accounts(accounts):
        # Placeholder method to simulate DML update in Salesforce
        # In a real Salesforce environment, this would interact with Salesforce APIs
        # Here, we just print the updated accounts for demonstration purposes
        For account in accounts:
            Print(f”Updated Account: {account}”)
        Return True # Assuming update is successful for demonstration
Def main():
    Accounts_to_update = []
    # Assuming Trigger.new is a list of updated Account objects
    Trigger_new = get_trigger_new() # Method to simulate Trigger.new
    # Iterate through Trigger.new to find records to update
    For new_account in trigger_new:
        # Check if the account type is ‘Customer’ and status is ‘Active’
        If new_account.type == ‘Customer’ and new_account.status == ‘Active’:
            # Modify the record – for example, change the priority to ‘High’
            New_account.priority = ‘High’
            # Add the modified record to the separate list
            Accounts_to_update.append(new_account)
    # Perform DML operation on the separate list of accounts to update
    If accounts_to_update:
        # Assuming SalesforceService.update_accounts() is a method to perform DML update
        Update_success = SalesforceService.update_accounts(accounts_to_update)
        If update_success:
            Print(“Accounts updated successfully!”)
        Else:
            Print(“Failed to update accounts. Check logs for details.”)
Def get_trigger_new():
    Trigger_new = []
    # Add some Account objects to simulate Trigger.new
    Account1 = Account(“Account1”, “Customer”, “Active”)
    Account2 = Account(“Account2”, “Supplier”, “Inactive”)
    Account3 = Account(“Account3”, “Customer”, “Active”)
    Trigger_new.extend([account1, account2, account3])
    Return trigger_new
If __name__ == “__main__”:
    Main()


Your Answer