Monday, October 28, 2019

WHAT IS BEFORE INSERT EVENT IN APEX TRIGGER, EXPLAIN IT WITH AN EXAMPLE?


BEFORE INSERT:

This event runs the block of code before inserting data into the database. Operations such as validation can be performed under this event to prevent wrong entry inside the database.

SYNTAX:


trigger triggerName on objectName (before insert) {
   // Block of code
}



Let us understand with a simple example:

SCENARIO:

We are having the requirement to write a trigger on the lead object to prevent the creation of lead in “Closed - Converted” status. We will be writing a trigger to achieve this requirement.

APEX TRIGGER:


trigger leadMainTrigger on Lead (before insert) {    // Event is before insert.

    validateLeadData obj=new validateLeadData();  // Declaring the instance of class.

    if(trigger.isbefore && trigger.isinsert) // Using context variables.

    {

     obj.method1(trigger.new); // Calling apex class method using instance of class.

    }

}


APEX CLASS:

public class validateLeadData {

    public void method1(List<Lead> leadList){ //Getting lead records list from trigger.new.

        for(Lead obj:leadList){ // Iterating over lead list.

            if(obj.status=='Closed - Converted'){ // checking the status.

                obj.addError('Lead cannot be created in "Closed - Converted" status. Please select other status'); // Throw error if condition is satisfied.

            } 

        }

    }

}


Now let us try to create a lead record in "Closed - Converted" status.

before insert trigger salesforce example

before insert and after insert trigger in salesforce


No comments:

Post a Comment