In this is post , I have given very simple examples for learning salesforce Apex Triggers concepts.
Apex Triggers saves lots of time involving in automating complex businuess process
Examples
- Use case 1:
when account is inserted, automatically contact also created for that account.
{
Contact cont = new Contact( );
}
- Explanation:
Above one is a simple trigger to insert contact when you create account . the text which is mentioned in green color is trigger name. And text which is mentioned in red color is event name.
Trigger. New is a context variable. which returns a list of new records of the sobjects which we are going to insert into the database.
- Use Case 2:
- Create a trigger on opportunity that throws
error if Amount is less than 5000
{
{
}
}
- Explanation:
Above one is a simple trigger which fires if Opportunity values is less than 5000 k. This is trigger triggers every time when record is created and updated
- Use Case 3:
- If a New record is created, Amount should not be less than 5k If an Existing record is being updated
, Amount should not be less than 3k
{
{
}
}
4. Use Case 4:
- Create a contact record on New Opportunity Insert
{
Contact c = new Contact( );
{
}
}
Introduction to Triggers:
Apex Trigger is an action which gets fired on the particular event. In salesforce trigger is apex code that executes before or after the below types of operations.
- Insert
- Update
- Delete
Undelete
Triggers will run before object records are inserted, updated, deleted into the database or after records are inserted, updated, deleted and restored.
- Apex Triggers can be classified into two types:
- Before triggers can be used to update or validate record values before they are saved to the database.
- After triggers can be used to access field values that are set by the database, and to effect changes in other records.
- Events in triggers:
- Before Insert, Before Update, Before Delete
- After Insert, After Update, After
, After Undeletedelete
- When to use “before”
“after” triggers:vs
- Syntax to create
:sample trigger - Use below syntax to create
.trigger trigger ObjectName (<eveon s>){nt
// Code Goes Here :)
}
- Trigger Context Variables:
- All tri
gge rs define implicit variables that allow users to access run time context. These variables are contained in the ystem.trigger class.S - T
igger.Newr - T
igger.oldr - T
igger.NewMapr - T
r igg er. OldMap - T
r igg er.i sAfter - T
r igg er.is Before - T
r igg er.is Insert - T
r igg er.is Update - T
r igg er.is Delete - T
r igg er.isUn delete.
========================================================================
