Newer Version Available
Add an Apex Trigger
- A Salesforce account in a sandbox Professional, Enterprise, Performance, or Unlimited Edition org, or an account in a Developer org.
- The MyHelloWorld Apex class.
A trigger is a piece of code that executes before or after records of a particular type are inserted, updated, or deleted from the Lightning Platform database. Every trigger runs with a set of context variables that provide access to the records that caused the trigger to fire. All triggers run in bulk; that is, they process several records at once.
- From the object management settings for books, go to Triggers, and then click New.
-
In the trigger editor, delete the default template code and enter this trigger
definition:
1trigger HelloWorldTrigger on Book__c (before insert) { 2 3 Book__c[] books = Trigger.new; 4 5 MyHelloWorld.applyDiscount(books); 6}The first line of code defines the trigger:
1trigger HelloWorldTrigger on Book__c (before insert) {It gives the trigger a name, specifies the object on which it operates, and defines the events that cause it to fire. For example, this trigger is called HelloWorldTrigger, it operates on the Book__c object, and runs before new books are inserted into the database.
The next line in the trigger creates a list of book records named books and assigns it the contents of a trigger context variable called Trigger.new. Trigger context variables such as Trigger.new are implicitly defined in all triggers and provide access to the records that caused the trigger to fire. In this case, Trigger.new contains all the new books that are about to be inserted.
1Book__c[] books = Trigger.new;The next line in the code calls the method applyDiscount in the MyHelloWorld class. It passes in the array of new books.
1MyHelloWorld.applyDiscount(books);