Activity › Forums › Salesforce® Discussions › How can i use same SOQL script for both before and after triggers that are run on same object?
Tagged: Lazy Load, Salesforce Force.com, Salesforce Trigger, SOQL
-
How can i use same SOQL script for both before and after triggers that are run on same object?
Posted by Audrey on March 16, 2016 at 7:44 AMI have use case in which I have to query Lead data and have to fire both before and after trigger on the same object. Any way to do that using a same SOQL Statement? Do I have to hardcode two different queries?
Parul replied 7 years, 9 months ago 3 Members · 2 Replies -
2 Replies
-
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 ListLeaddata= [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) {
listLeaddata = 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 ListlazyQueues {
get {
if (lazyQueues == null)
lazyQueues = [Select Id,Name from Lead LIMIT 10];
return lazyQueues;
}
private set;
}
public static void rebuildingCaches() {
lazyQueues == null;}
}`
- [adinserter block='9']
-
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.