Define Salesforce Apex Trigger with example ?

630    Asked by AbigailAbraham in Salesforce , Asked on Feb 1, 2020
Answered by Abigail Abraham

 In salesforce, the apex trigger is a piece of code or set of instructions which is written in apex platform that runs before or after and performs specific data manipulation language events. It might be events like where before object records are inserted into the salesforce database, or after insert or after records have been deleted from salesforce database.

Apex trigger is responsible to perform the custom action which salesforce developers couldn’t achieve using point and click functionality of salesforce like workflow,validation rule or process builder. Also, the trigger is to perform the custom actions before or after events to records in Salesforce, such as insertions, updates, or deletions. It's similar to database systems support triggers, Apex provides trigger support for managing records. If you want to update a field or check data for a particular field then better to use workflow or validation rules. So typically we use triggers to perform some task based on some condition or we can restrict users to perform tasks and display messages as well in the user interface.

Salesforce all standard objects like account, contact, Opportunity and also custom objects support triggers and we can easily create them. Once the trigger has been created then by default it will be active.

Also, it’s always advisable from salesforce that don’t write complex business logic directly into triggers rather than use a separate class(called handler class) which will handle the logic and call that class within apex triggers.We will learn about this in detail in the later section.

Trigger Syntax :-

 Trigger trigger_name on objectName (triggerEvent){
 //Business logic or code block
}
Example :-
In this example, Suppose we have a custom field Hello_c field is present on account and now update this field with value ‘World’ whenever a new account is created or updated by a user.
trigger myfirst trigger on Account (before insert, before update)
{

 List acc = Trigger.new;
 My Trigger Logic my= new Mytriggerlogic(); //creating instance of apex class
 myt.addHelloWorldkeyword(acc); // calling method from the apex class
 }
Handler Class with logic :-
public class Mytriggerlogic
 {
 public void addHelloWorldkeyword(List acc)
 {
 for (Account a:acc)
 {
 if (a.Hello__c != 'World')
 {
 a.Hello__c = 'World';
 }
 }
 }
 }


Your Answer

Interviews

Parent Categories