Skip to main content
Build the future with Agentforce at TDX in San Francisco or on Salesforce+ on March 5–6. Register now.

Use sObjects and DML

Learning Objectives

After completing this unit, you'll be able to:

  • Define sObject.
  • Explain the difference between sObjects and other Apex data types.
  • Use DML to insert records into the database.

Follow Along with Trail Together

Want to follow along with an expert as you work through this step? Take a look at this video, part of the Trail Together series on Trailhead Live.

(This clip starts at the 21:39 minute mark, in case you want to rewind and watch the beginning of the step again.)

What's an sObject?

An sObject is an Apex data type that corresponds to a Salesforce object (sObject) in an org. sObjects are complex data types that hold multiple values in one variable. They hold a single record of data from a Salesforce object, such as an Account, a Contact, or an Opportunity. Remember from Apex Basics for Admins that variables are like containers. Most variables hold one piece of information. sObjects are containers that hold other containers. The containers within the sObject container may be of different data types, such as string, date, integer or Boolean.

sObject square with four boxes inside labeled, Id, Name, Type and Custom_Field__c

New Accounts

Name

Account Number

Phone

The Tea Factory

356281

555-0158

Tina's Teas

623956

555-0129

Look at the information in this table. If you've used Data Loader, you're familiar with this account format. The account fields are Name, Account Number, and Phone. The data is what you'd see if you retrieved the information from a report or list view.

An object's fields in an org are called sObject properties in Apex code. As each field in an org's object has a data type, each sObject property has a data type. For example, because the Name field of an Account object has the string data type, the Name property of the myAcct sObject also has the string data type: myAcct.Name = 'The Tea Factory'.

Whether you create an account manually (in the Salesforce user interface) or programmatically (using Apex code), you set the same values, with the same data types. For example, in the Salesforce user interface, you can create an account with the field values in the first row of the New Accounts table above. To create the same account programmatically, use an Account sObject in Apex code, like this:

Account myAcct = new Account();
myAcct.Name = 'The Tea Factory';
myAcct.Phone= '555-0129';
myAcct.AccountNumber = '356281';

Use the sObjectName, dot notation, and the same default fields (Name, Phone, and AccountNumber) that you are already familiar with in your org.

Account myAcct = new Account(); myAcct.Name = 'The Tea Factory'; myAcct.AccountNumber = '356281'; The sObject name is myAcct and the sObject properties are Id, Name, Phone and AccountNumber

In this example, the myAcct properties (Name, Phone, and AccountNumber) have data types that you're familiar with: string and integer.

Set Field Value

Use dot notation to assign a value to an sObject. In the previous code sample, look at lines 2-4. If we think of the sObject as a container of containers, those lines open the largest container, myAcct, find the Name, Phone, and AccountNumber containers, and add values to them.

Get Field Value

Similarly, use dot notation to get (retrieve) a value from an sObject.

Example: String accountName = myAcct.Name;

This code sample opens the myAcct container, looks inside the container, finds the Name container, and gets its value. In this example, the value returned is The Tea Factory.

Declaring an sObject is like adding a row to a spreadsheet. When you're ready to create another account, give the Account object a new name. For example:

Account myAcct2 = new Account();
myAcct2.Name = 'Tina\'s Teas';
myAcct2.AccountNumber = '623956';
myAcct2.Phone = '555-0129';

Adding Data to a Salesforce Org

Are you ready to write Apex code to add data to your Salesforce org? You know how to create classes, create methods, and declare an sObject. But how do you add an sObject to your Salesforce database? To send new records to your Salesforce org, you use a thing called data manipulation language (DML).

As an admin, you are already familiar with DML. You know it as the Insert (create a record), Update (edit a record), and Delete (delete a record) statements that you use with data manipulation tools, such as Data Loader. Instead of using .csv files and Data Loader to add rows or to insert or update records, you can write Apex code to do the work. Use Apex code and the DML Insert, Update, and Delete statements. Pretty cool! In this unit, we focus on the Insert statement.

Define the Class

  1. In the Developer Console, click File | New | Apex Class.
  2. Enter NewAccounts for the class name.
  3. Click OK.
  4. Replace the default code with this code:
    public class NewAccounts {
        public static void sObjectsInsert(){
            Account store = new Account();
            store.Name = 'The Tea Factory';
            store.AccountNumber = '356281';
            store.Phone = '555-0158';
            insert store;
        }
    }
  5. Click File | Save.

Now you have a NewAccounts class that creates a new record and sets its properties. The class also uses the insert statement to add the new account record to the database. Time to run your code!

Run the Code

  1. Click Debug | Open Execute Anonymous Window.
  2. In the Enter Apex Code window, paste this code:
    NewAccounts.sObjectsInsert();
  3. Click the Open Log checkbox and click Execute.
  4. From the App Launcher, find and open Accounts. The Tea Factory appears in the Accounts list. (If you don't see The Tea Factory, refresh the page.)
    On the Accounts page, The Tea Factory is displayed under Recently Viewed Accounts.
  5. Click The Tea Factory.
  6. Click Details. Notice that the Account Name, Phone, and Account Number fields show the values that you set as sObject properties in the NewAccounts class.

Use a Loop to Create Multiple Records

Adding one account at a time isn't very practical. Usually, you need to create many accounts at a time, by either importing or updating records.

You could add multiple records the same way that we added one record in the previous example, but you'd need to repeat the code for each record, like this:

Account store1 = new Account();
Account store2 = new Account();
store1.Name = 'The Tea Factory 1';
store1.AccountNumber = '356281';
store1.Phone = '555-0158';
store2.Name = 'The Tea Factory 2';
store2.AccountNumber = '356282';
store2.Phone = '555-4012';
insert store1;
insert store2;

In Apex Basics for Admins, you learned about loops and lists. Here's an opportunity to use those concepts. Using a while loop and a list, you can create many records at one time, and add all of the records to your database. It's like using Data Loader to upload a .csv file that includes three records and insert them into the database.

Write the Method

  1. Return to the NewAccounts class in the Developer Console.
  2. Replace the existing code with this code:
      public class NewAccounts {
        public static void sObjectsInsert(Integer value){
            Integer counter = 1;
            //create a list to add our accounts
            List<Account> teaFactoryAccounts = new List<Account>();
            while(counter <= value){
                //display the current counter value
                System.debug('Counter Value before Incrementing ' + counter);
                //create a new account
                Account store = new Account();
                store.Name = 'The Tea Factory ' + counter;
                store.AccountNumber = '35629' + counter;
                teaFactoryAccounts.add(store);
                System.debug(teaFactoryAccounts);
                //increment the counter
                counter = counter + 1;
                System.debug('Counter Value after incrementing ' + counter);
            }
            System.debug('Size of Account List: ' + teaFactoryAccounts.size() );
            System.debug('Elements in Account List: ' + teaFactoryAccounts);
            //insert all of the accounts in the list
            insert teaFactoryAccounts;
        }
    }
  3. Click File | Save.

Run the Method.

  1. Click Debug | Open Execute Anonymous Window.
  2. In the Enter Apex Code window, paste this code:
    NewAccounts.sObjectsInsert(3);
  3. Select Open Log and then click Execute. The log window opens.
  4. Select Debug Only.

The last entry in the log shows that the code created three accounts with a name and account number for each account:

The Tea Factory 1, 356291

The Tea Factory 2, 356292

The Tea Factory 3, 356293

The teaFactoryAccounts list created in line 5, looks like this:

A space subdivided into three slots with one account in each slot. Slot 1: Name = The Tea Factory 1, AccountNumber = 356291. Slot 2: Name = The Tea Factory 2, AccountNumber = 356292. Slot 3: Name = The Tea Factory 3, AccountNumber = 356293.

Each time the value of the counter variable is incremented, an sObject is created in the next open index (position) in the list.

Return to the Accounts list in your Trailhead Playground org and click Accounts. The three restaurants you inserted are included in the Accounts list.

Review the Loop Code

Examine the while loop code. It instantiates a new Account sObject named store. Next the loop sets the name 'The Tea Factory'. To differentiate the account records, it adds the current counter value to the end of the store.Name string during each iteration of the loop.

After the properties are set, teaFactoryAccounts.add adds a store sObject to the teaFactoryAccounts list during each iteration of the while loop, until the loop condition is met when the value is greater than or equal to the counter.

Note

Don't forget to increment the counter in the while loop. If our example code didn't continually add one to the counter, then the condition would never be met. The while loop would continue adding records until the time limit set by Salesforce was reached.

When the condition is met, the while loop ends and the last line inserts the teaFactoryAccounts list into the database all at once.

Why all at once? Because resources are limited, you can use the insert statement in your code only 150 times. One record at a time, you can insert a total of 150 records. But if each insert statement inserts 10 records, that total increases to 1,500 records. Inserting multiple objects at once helps with bulkification (combining repetitive tasks by writing efficient code). At first you may be inserting as few as 10 records at a time. But as your application grows, you might begin to insert 200 records at a time. Using bulkification from the start prepares your application for growth.

Resources

Condividi il tuo feedback su Trailhead dalla Guida di Salesforce.

Conoscere la tua esperienza su Trailhead è importante per noi. Ora puoi accedere al modulo per l'invio di feedback in qualsiasi momento dal sito della Guida di Salesforce.

Scopri di più Continua a condividere il tuo feedback