Friday, 22 August 2014

How to do DML Operation when a Page loads

Hi All,

Here is a scenario that I have come across, there was a need to do DML operation when a vf page loads.

How will we achieve it ?

As we all know when a page loads, constructor executes first but we can not write DML statement in constructor,however there is another approach for the above requirement. 

Here is the Page. 
<apex:page controller="DMLStatementOnPageloadController" action="{!createAccount}">
createAccount will be invoked when page loads.

public with sharing class DMLStatementOnPageloadController {

    public PageReference createAccount(){
        Account acc = new Account(name = 'DMLStatementOnPageload');
        insert acc ;
        return null;