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}">
</apex:page>

Controller:

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