You create an Apex trigger in a sandbox or scratch org, then deploy it to production with test coverage. The simplest way to start is the Developer Console, which scaffolds the trigger for you on the object and events you pick.
- Open the Developer Console
From the Setup gear menu, choose Developer Console. Go to File, then New, then Apex Trigger. This is the quickest place to author and save a trigger in a sandbox.
- Name the trigger and pick the object
Enter a clear name such as AccountTrigger, then select the sObject it runs on, for example Account. A trigger is bound to exactly one object and cannot span several.
- Declare the events
In the generated trigger header, list the events inside parentheses, such as (before insert, before update, after insert). Each event sets a timing and a DML operation the trigger responds to.
- Branch and call a handler
Inside the body, check the context with flags like Trigger.isBefore and Trigger.isInsert, then call a handler class method. Keep business logic in the handler, not in the trigger.
- Write tests and deploy
Create a test class that inserts and updates 200 records to prove the trigger is bulk safe. Production deployment requires at least 75 percent code coverage across your Apex.
A unique API name for the trigger, used as the file name and in metadata. Pick a convention like ObjectTrigger so each object has one obvious trigger.
The single object the trigger runs on. The trigger fires only for DML on this object, and you cannot change the object after creation without recreating the trigger.
One or more of before insert, before update, before delete, after insert, after update, after delete, after undelete. At least one event is required for the trigger to do anything.
- You cannot deploy a trigger straight into a production org by editing it there. Author it in a sandbox or scratch org, then deploy with tests.
- Trigger.new is read only in after contexts. To change field values on the record being saved, do it in a before trigger instead.
- There is no after merge or after upsert event. A merge fires delete and update triggers, and an upsert fires insert and update triggers.