Writing Apex Triggers
Typically, you use triggers to perform operations based on specific conditions, to modify related records or restrict certain operations from happening. You can use triggers to do anything you can do in Apex, including executing SOQL and DML or calling custom Apex methods.
Use triggers to perform tasks that can’t be done by using the point-and-click tools in the Salesforce user interface. For example, if validating a field value or updating a field on a record, use validation rules and workflow rules instead.
Triggers can be defined for top-level standard objects, such as Account or Contact, custom objects, and some standard child objects. Triggers are active by default when created. Salesforce automatically fires active triggers when the specified database events occur.
Trigger Syntax
trigger TriggerName on ObjectName (trigger_events) {
code_block
}
Please refer the following link to learn more about trigger programming How to show error message in trigger .
- before insert
- before update
- before delete
- after insert
- after update
- after delete
- after undelete
Example
This simple trigger fires before you insert an account and writes a message to the debug log.
- In the Developer Console, click .
- Enter HelloWorldTrigger for the trigger name, and then select Account for the sObject. Click Submit.
- Replace the default code with the following.
trigger HelloWorldTrigger on Account (before insert) {
System.debug(‘Hello World!’);
}
4. To save, press Ctrl+S.
5. To test the trigger, create an account.
Click
.In the new window, add the following and then click Execute.
Account a = new Account(Name=’Test Trigger’);
insert a;
6.In the debug log, find the Hello World! statement. The log also shows that the trigger has been executed.
Types of Triggers
There are two types of triggers.
- Before triggers are used to update or validate record values before they’re saved to the database.
- After triggers are used to access field values that are set by the system (such as a record’s Id or LastModifiedDate field), and to affect changes in other records. The records that fire the after trigger are read-only.
We are the ISV Partners and Please reach us for custom development => www.merfantz.com
This training information is very useful to learn about Trigger creation in salesforce.