Select your language

  • Davide Gammone

            

Davide Gammone.com
How to resolve the Too Many DML statements: 1 error in Salesforce

When you write and test your code in Salesforce, did you ever get the "Too Many DML Statements: 1" error? Usually the error occurs with: Lightning Components, Lightning Web Components, and Visualforce Page.





Visualforce Page

<apex:page controller="InsertAccount" readOnly="true">
    <h1>Ciao {!$User.FirstName}</h1>    
    <p>Inserisci i dati del Candidato</p>
    <apex:form>
        Name: <apex:inputField value="{!acc.Name}"/>
        <apex:commandButton action="{!save}" value="Save"/>
    </apex:form>
</apex:page>

Apex Class

public class InsertAccount{
    public Account acc {get; set;}
    public InsertAccount() {
        acc = new Account();
    }
    public void save(){ 
        insert acc; 
    }
}

If we test the code written above, we have the following error in the Visualforce Page:

Visualforce Error System.LimitException: Too many DML statements: 1
Error is in expression '{!save}' in component <apex:commandButton> in page test: Class.InsertAccount.save: line 7, column 1

If you are facing the same issue then please check whether you have made readOnly attribute of apex:page tag as true. If so, then just make it readOnly="false".

While Visualforce Pages that use read-only mode for the entire page can’t use data manipulation language (DML) operations, they can call getter, setter, and action methods which affect form and other user interface elements on the page, make additional read-only queries, and so on.

Lightning Components / Web Components

public class updateAccount{
    @AuraEnabled(cacheable=true)
    public static void updateAccounts(){
        List<Account> lstAcc = new List<Account>();
        for(Account acc:[SELECT Id, Name FROM Account Limit 1]){
            acc.Name = 'LWC_Test';
            lstAcc.add(acc);
        }
        if(!lstAcc.isEmpty()){
            update lstAcc;
        }
    }
}

In this or similar case, to resolve the error, simply remove the cacheable=true parameter from your @AuraEnabled annotation.

The general guideline is to cache (mark as storable) any action that is idempotent and non-mutating.

An idempotent action is an action that produces the same result when called multiple times. For example:

  • getPage(1) is idempotent and should be cached
  • getNextPage() is not idempotent and should not be cached

A non-mutating action is an action that doesn’t modify data. Never cache an action that can create, update, or delete data. For example:

  • updateAccount(sObject) is mutating and not idempotent and should not be cached.

GDPR Alert

This site uses cookies, including third-party requests, to offer you services in line with your preferences. By closing this banner, scrolling this page or clicking any element, you consent to the use of cookies. If you want to learn more or opt out of all or some cookies, click on Privacy Policy...