November 2, 2016 by LanceShi
1.4 DML executes in one transaction
One important concept about DML is it will be executed in one transaction. So if you insert or update or delete a list of records, it either all succeed or all fail.
Below is a experiment on this. To do this, we need to setup a validation rule on our Merchandise object. Let’s setup a validation rule to validate the original price is no lower than 50 dollars in order to have a discount. If you don’t know how to do it, follow the screenshot below:
Then we can write relevant code to test this:
Merchandise__c mer = new Merchandise__c(); mer.name = 'Books'; mer.Original_Price__c = 20; Merchandise__c mer2 = new Merchandise__c(); mer2.name = 'Bike'; mer2.Original_Price__c = 300; List<Merchandise__c> merList = new List<Merchandise__c>(); merList.add(mer); merList.add(mer2); insert merList;
Execute the code in anonymous block and you will get the validation error. Turn to Salesforce platform, you can find that neither of the records are inserted.