Writing a Simple Apex Trigger !!
Writing a Simple Apex Trigger !!
Now we know where to write a Trigger, let’s begin with a simple example. In this scenario I would like to add a custom text in the last name of a contact.
Let’s have a look at the basic structure of a trigger
trigger MyCustomTriggerName on CustomObject__c (trigger_events) {
Line of codes to execute(Business Logic)
}
Using the above-mentioned structure we will write our code, in the above code we can give Trigger any name we want, and since we want the trigger to be on contact standard object, the structure of trigger looks like below
trigger ContactTestTrigger on contact (before insert) {
Line of codes to execute(Business Logic)
}
Now that we have defined the basic structure of the trigger now we will write the business logic as discussed in the beginning.
trigger ContactTestTrigger on contact (before insert) {
for(contact con : Trigger.new){
con.lastname = ‘New Last Name using Trigger’;
}
}
This is it, we have written a simple Trigger which initiates at before insert event of a contact. Based on the occurrence of the DML event, there are broadly two types of Triggers; Before Trigger and After Trigger. Further, the trigger can be classified into the below groups based on the events.
- Before insert, after insert.
- Before update, after update.
- Before delete, after delete.
- Before undelete.
In Trigger, we can modify the data without explicitly calling any DML operation, and if the operation is performed then it results in an error. The record is committed to the database once the trigger has completed its execution
Here you also see the use of a variable Trigger.new in the for loop, it is a trigger’s context variable. Trigger’s context variable holds the values of the record which initiated the execution of the trigger, for e.g. Trigger.New contains the list of contacts which initiated the trigger. There are some Trigger’s context variables which return Boolean values and with the help of context variables, we can determine which event fired the trigger. There are many context variable available in Salesforce and can be studied in detail here.
This concludes how to write a Simple Trigger
Next, I would like to present, how to call apex class method in trigger, callout, and using trigger exceptions
find interview Questions on Trigger here
Interview Questions Apex Trigger
Also, Have a look at the below learning resources:
-
SOQL (Salesforce Object Query Language)
-
Apex Trigger Best Practices and the Trigger Framework
-
Salesforce Interview Question and Answers Part 2
-
Salesforce Interview Questions on Test Class
-
Salesforce-lightning-interview-questions-2018
[…] Writing a Simple Apex Trigger !! […]
[…] us with Trigger. There are two places where you can write Trigger: SandboxDeveloper Edition. Writing a Simple Apex Trigger !! Writing a Simple Apex Trigger !! Now we know where to write a Trigger, let’s begin with a […]