Create a Trigger
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 28:13 minute mark, in case you want to rewind and watch the beginning of the step again.)
Add the Trigger
Because code in a trigger is bound by Apex transaction, it is subject to governor limits. To reduce the incidence of governor limit exceptions, a Salesforce best practice is to avoid instantiating an object within a trigger.
Instead, invoke a trigger handler from the trigger, and instantiate objects in the handler. When we use a trigger, we call the method in the trigger handler using the static keyword. With the static keyword, we avoid instantiating the class into an object, which helps to prevent governor limit exceptions.
Create the CreateContact trigger to invoke the createContact method.
- In the Developer Console, click File | New | Apex Trigger. The New Apex Trigger window opens.
- For Name, type
CreateContact
. - For sObject, select Candidate__c.
- Click Submit.
- Replace the existing code with this code:
trigger CreateContact on Candidate__c (after insert){ /* Invoke the createContact method with a list of Candidates as the argument to create a corresponding Contact from each new Candidate Record */ CreateContactFromCan.createContact(Trigger.new); }
- Save the trigger.
Create a new candidate to test the trigger.
- From App Launcher (), find to open Candidates.
- Click New.
- Create a candidate record as follows:
- First Name:
Gina
- Last Name:
Simmons
- Email:
gsimmons@test.com
- First Name:
- Click Save.
- From App Launcher (), find and open Contacts.
- Select the All Contacts list view.
- Verify that a contact named Gina Simmons was created.
Summary
Congratulations! You created your first Apex code and used the Developer Console to evaluate code snippets. To learn more about Apex, check out the Apex Basics for Admins module.