Tag Archives: DML

sObjects That Don’t Support DML Operations

Following standard objects don’t support DML operations, but it supports SOQL query.

  • AccountTerritoryAssignmentRule
  • AccountTerritoryAssignmentRuleItem
  • ApexComponent
  • ApexPage
  • BusinessHours
  • BusinessProcess
  • CategoryNode
  • CurrencyType
  • DatedConversionRate
  • NetworkMember (allows update only)
  • ProcessInstance
  • Profile
  • RecordType
  • SelfServiceUser
  • StaticResource
  • Territory2
  • UserAccountTeamMember
  • UserTerritory
  • WebLink

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

Create Parent And Child Record In A Single DML Statement Using External ID

Sample Code

//Parent Account
Account acc = new Account();
acc.Name = 'Salesforce';
acc.ExternalID__c = '12333';//External Id

//Child Contact
Contact con = new Contact();
con.FirstName = 'John';
con.LastName = 'Doe';
con.Account = new Account(ExternalID__c = '12333');

List<Database.SaveResult> results = Database.Insert(new SObject[] {acc, con});

for (Integer i = 0; i < results.size(); i++) {
    if (results[i].isSuccess()) {
        System.debug('Successfully Created record ID: '+ results[i].getId());
    } 
}

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