Skip to main content

Use DML to Save sObjects to 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.

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

Create and Adjust the sObjects

Create a Recruiting Account sObject and save it to the database. 

  1. In the Developer Console, open the Execute Anonymous window.
  2. Replace the existing code with this code:
    //From the Account class, instantiate an object named acct
    Account acct = new Account();
    //Set the name attribute of the acct object to Recruiting
    acct.name='Recruiting';
    //Use DML to save the acct object to the database
    Database.insert(acct);
    System.debug('A new account named ' + acct.name + ' was added ');
  3. Verify that Open Log is selected and then click Execute. The execution log opens.
  4. Select Debug Only.
  5. Review the debug message and then close the log.

Within the createContact method, create a Contact sObject, populate its attributes, add it to the conList, and save the list to the database.

  1. In the CreateContactFromCan class, replace the existing code with this code:
    public with sharing class CreateContactFromCan {
        //Declare a method that returns void and accepts a Candidate list named candsFromTrigger
        public static void createContact (List<Candidate__c> candsFromTrigger) {
            //Instantiate a Contact list named conList
            List<Contact> conList = new List<Contact>();
            //Declare a list FOR loop that uses an iteration variable named currentCandidate
            //to loop through the candsFromTrigger list
            for(Candidate__c currentCandidate:candsFromTrigger) {
                //Create a Contact and add it to conList
                //Set the FirstName, LastName, and Email attributes to match the
                //corresponding attributes of the currentCandidate object (First_Name__c,
                //Last_Name__c, and Email__c)
                conList.add(new Contact(
                    //Set the AccountId for the contact(we'll do this in the next unit)
                    //AccountId = candAccts[0].Id,
                    FirstName = currentCandidate.First_Name__c,
                    LastName = currentCandidate.Last_Name__c,
                    Email = currentCandidate.Email__c)
                );
            }
            //Save conList to the database
            Database.insert(conList);
        }
    }
  2. Save the CreateContactFromCan class.
Keep learning for
free!
Sign up for an account to continue.
What’s in it for you?
  • Get personalized recommendations for your career goals
  • Practice your skills with hands-on challenges and quizzes
  • Track and share your progress with employers
  • Connect to mentorship and career opportunities