Tag Archives: DML

Partial Apex DML Example in Salesforce

List <Account> conList = new List <Account> {
 new Account(Name = 'Test Account1', Phone = '8888888888', Industry = 'Agriculture'),
 new Account(Name = 'Test Account2', Phone = '7777777777', Industry = 'Banking'),
 new Account(Name = 'Test Account3', Phone = '9999999999', Industry = 'Finance'),
 new Account()
};

Database.SaveResult[] srList = Database.insert(conList, false);

for (Database.SaveResult sr : srList) {
 if (sr.isSuccess() ) {
  //Develop code for successfully inserted Accounts
  System.debug('Successfully inserted Account ' + sr.getId());
 } else {
  for (Database.Error err : sr.getErrors()) {
   //Develop code for failed Accounts
   System.debug(err.getStatusCode() + ' : ' + err.getMessage() + ' : ' + err.getFields());
  }
 }
}

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;
    }
}