Insert Statements
Not Started

To insert records into the database, we'll use the insert DML statement.

To do so, we'll first create a new sObject in memory. If you forgot what that means, refer to Into to sObjects.

Account newAcc = new Account(Name='Apple Inc'); newAcc.website = 'www.apple.com';

then reference the newAcc variable in our DML statement:

Account newAcc = new Account(Name='Apple Inc'); newAcc.website = 'www.apple.com'; insert newAcc;

Just like that, a new account record will be created in Salesforce. Well, kinda. The protect data integrity on the platform, the records undergoing DML are only committed to the database when the transaction is completed without errors.

Order of Execution and the Save Procedure

When Apex issues a DML statement, the affected records go through the "save" procedure. In the above scenario, any automation triggered upon account creation (custom triggers, flows, validation rules, duplicate rules, etc) will fire.

For example, say the newAcc example is called from a Screen Flow. When the DML happens, it fires off a series of other processes.

DML Order of Operations



If all automation runs without throwing an exception, the data will be committed to the database. You can read more on that in Salesforce's Order of Execution doc. Here's another great visual from Salesforce Ben

When the insert operation executes, the Id field is auto-generated and auto-populated on the sObject variable(s).

Account acc = new Account(Name='Apple Inc'); acc.website = 'www.apple.com'; System.debug(acc.Id); // prints out null insert acc; System.debug(acc.Id); // prints out the 18 digit Id of the account record

This comes in handy when we want to insert related sObjects. Say you want to create a Contact tied to the Account you just created:

Account acc = new Account(Name='Apple Inc'); acc.website = 'www.apple.com'; insert acc; Contact newContactRecord = new Contact(LastName='Attar'); newContactRecord.email = 'saman@campapex.org'; newContactRecord.AccountId = acc.Id; insert newContactRecord;

This is pretty common when writing test classes in Apex, but you'll see it in many Apex Controllers and Apex Triggers, too.

Challenge

The BookController class has a createBook methods you'll need to implement.

The method accepts the book's title and publisherId. Use these parameters to insert a single CAMPX__Book__c record and set it's CAMPX__Title__c and CAMPX__Publisher__c fields.

If you have not yet done so, you must install the managed package for this lesson's challenges.