DML Operation On Visualforce Page Load In Salesforce

As we know when VF page loads, constructor executes first. But we cannot write DML statement in constructor. Due to security issues, Salesforce does not allow DML operation in construtor.

Here is an workaround to do DML operation on VF page load. We can call apex method with DML operation using action attrirbute in VF page.

Visualforce Page:

<apex:page controller="SampleController" action="{!createAccount}">


public class SampleController {
    public SampleController(){
    public PageReference createAccount(){
        System.debug('DML Operation Method');
        Account acc = new Account(Name = 'Salesforce');
        Insert acc ;
        return null;

  • Aakash Chandnani

    This will result in an issue later in Code Quality as – No DML operations should be performed in constructor. How to resolve those errors?

    • Hi Aakash,

      In above code DML is not in the constructor, it is in page action method. It will not cause problem. Try with above logic.