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.
- In the Developer Console, open the Execute Anonymous window.
- 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 ');
- Verify that Open Log is selected and then click Execute. The execution log opens.
- Select Debug Only.
- 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.
- 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); } }
- Save the CreateContactFromCan class.