Activity Forums Salesforce® Discussions How can i use same SOQL script for both before and after triggers that are run on same object?

  • Geek

    Member
    March 17, 2016 at 10:06 am

    A good practice is to create code that is as reusable as possible. So I would advise to keep query number as low as possible.
    So there are two ways you can run before and after triggers simultaneously, first is using static variable. You can include it in your trigger handler class.

    `Static Variable

    public class cachequery {
    public static List Leaddata= [Select Id,Name from Lead LIMIT 10];
    }

    You can then use it in the trigger something like this

    trigger T1 on Lead (before insert, after insert) {
    list Leaddata = cachequery.Leaddata;
    if(Trigger.isBefore && Trigger.isInsert){
    system.debug(Leaddata );
    }
    if(Trigger.isAfter && Trigger.isInsert){
    system.debug(Leaddata );
    }
    }`

    The other way is to use Lazy Loading
    Lazy loading is a technique to use cache in such a way that it your code consumes the query only when it actually need the data.

    `public with sharing class MyService {
    public static List lazyQueues {
    get {
    if (lazyQueues == null)
    lazyQueues = [Select Id,Name from Lead LIMIT 10];
    return lazyQueues;
    }
    private set;
    }
    public static void rebuildingCaches() {
    lazyQueues == null;

    }
    }`

  • Parul

    Member
    September 7, 2018 at 11:08 am

    Hi Audrey,

    There is different DML operations i.e. Insert,Update,Delete on which any Trigger is fire,Out of these only for UPDATE we can write same SOQL for before and after Trigger.

    trigger checksameQuery on Lead (before update, after update) {

    List<Lead> listofLead = [Select id,FirstName,LastName from Lead where id =: Trigger.new];

    for(Lead leadObject : listofLead){
    if(Trigger.isBefore && Trigger.isupdate){
    System.debug('leadObject>>>>>>'+leadObject.FirstName);
    }
    if(Trigger.isAfter && Trigger.isupdate){
    System.debug('leadObject>>>>>>'+leadObject.FirstName);
    }
    }
    }

    In case of other INSERT DML we can use Trigger.New for both before and After Trigger

     

    rigger checksameQuery on Lead (before insert, after insert) {

    for(Lead leadObject : Trigger.New){
    if(Trigger.isBefore ){
    System.debug('leadObject>>>>>>'+leadObject.FirstName);
    }
    if(Trigger.isAfter ){
    System.debug('leadObject>>>>>>'+leadObject.FirstName);
    }
    }
    }

    Thanks

     

Log In to reply.

Popular Salesforce Blogs

Popular Salesforce Videos