Salesforce Trigger Scenarios | Simplified
Salesforce Scenario Based Triggers
In the previous Episode, we discussed how to use Delete event, Trigger.newMap, Trigger.oldMap and order of execution of triggers in salesforce.
In this episode, we will consider different trigger scenarios in salesforce and then break every trigger to understand the requirement.
Which will help you to understand when to use what while writing the triggers in salesforce.
let's get started...
Scenarios
Scenario 1 :
Create "Sales Rep" field with the data type(Text) on the Account object When we create the Account record, the Account owners will be automatically added to the sales rep field. When we update the Account owner of the record, then also the Sales Rep will be automatically updated.
Trigger :
=============================================
trigger UpdateSalesRep on Account(Before insert, Before update)
{
set<Id> setAccowner = new.set<Id>();
for(Account Acc : trigger.New)
{
setAccowner.add(Acc.ownerId);
}
Map<Id, user> usermap = new Map<Id, user>([SELECT Name FROM user WHERE Id IN: setAccowner]);
for(Account Acc : Trigger.New)
{
user usr = usermap.get(Acc.ownerId);
Acc.sales_rep__c = usr.Name;
}
}
}
============================================
Explanation :
Step 1 :
In the above trigger, as we want to fire the trigger before creating any Account record hence we used before insert trigger on Account object.
Similarly as per the second requirement i.e. for update event hence we are writing before update trigger on Account object.
trigger UpdateSalesRep on Account(Before insert, Before update)
Step 2 :
We used set to store Id's as we don't want duplicate Id's of AccountOwner.
Hence we created an instance of that as setAccowner.
Step 3 :
Then we used for loop for every new account hence we used trigger.new inside the loop.
Inside the loop, we are adding account ownerId in a set.
Step 4 :
Then we have created an instance of map usermap, which will store key=Id and value=user along with one query
SELECT Name FROM user WHERE Id IN: setAccowner
which will give you Name of the user whose Id is equal to Account OwnerId.
Step 5 :
Then in the next for loop, we created an instance for the user as usr. Which will be equal to the Account ownerId which we will get from map i.e. from Acc.ownerId.
Step 6 :
And at the end, we are saying sales_rep__c from an Account which will be equal to the user's name i.e. usr.Name.
In this way, we will achieve the above requirement very easily.
Isn't it very easy to write the triggers in salesforce ? Let's discuss the next trigger...
============================================
Scenario 2 :
Create a field called "Contact Relationship" checkbox on the contact object and create the object called "Contact Relationship" which is related list to the Contacts (Lookup Relationship).
Now build a logic when we create contact by checking Contact Relationship checkbox, then contact Relationship will be created automatically for that contact.
Trigger :
============================================
trigger CreateCRonContactCreation on Contact(after insert)
{
if(trigger.isAfter)
{
if(trigger.isInsert)
{
ContactMasterHandler ConIns = New ContactMasterHandler();
ConIns.createContactRelationshipByContact(trigger.new);
}
}
============================================
Apex Class :
============================================
public class ContactMasterhandler
{
public void createContactRelationShipByContact(List<contact> lstCon)
{
List<Contact_Relationship__c> conlist = new List<Contact_Relationship>();
for(Contact newcon : lstCon)
{
if(newcon.Contact_Relationship__c == true)
{
Contact_Relationship__c CR = new Contact_Relationship__c();
CR.Name = newcon.LastName;
CR.Contact__c = newConts.id;
ConList.add(CR);
}
}
insert ConList;
}
}
============================================
Explanation :
Before understanding the structure of the above scenario, I know it's a somewhat different example where we create apex class and just call the method wherever necessary. Which is makes your development easy. Also, it's very easy to understand for the developer as well.
Where your actual logic is written inside apex class and you and use it's methods wherever you want.
Advantage of doing this is, you can use the same apex class in different triggers as well for the same logic. No need to rewrite it.
Now let's discuss the above trigger...
Step 1 :
As per the requirement, we are performing an operation on the trigger when the user submits the record that means we need to use as after insert trigger.
Then when we need to check more about the event, hence we used a trigger.isAfter and trigger.isInsert to fire the trigger on only these particular events.
Step 2 :
Then we created an instance of apex class ContactMasterhandler as ConIns.
Then we called a createContactRelationshipByContact method from apex class where actual logic is written.
Step 3 :
Let's move towards apex method createContactRelationshipByContact where we are passing a list of contact in lstCon instance coming from new newly created contact.
Step 4 :
Then we have created an instance of List of Contact_Relationship__c as conlist which will store a list of Contact_Relationship__c records.
Step 5 :
After that, we created for loop for all the newly created contact in salesforce.
Step 6 :
Then if newcon.Contact_Relationship__c which is field from newly created contact. if it is true then it processes further and performs an action.
Step 7 :
Then we created an instance for Contact_Relationship__c object as CR.
Step 8 :
Then to create a new record for CR we are giving Name same as LastName of newly created contact.
Also, it's Contact is equal to the id of newly created contact.
Step 9 :
Then we added CR in list ConList and by Insert we successfully inserted Contact_Relationship__c record in salesforce.
Coool !! we just called the apex class inside trigger and performed DML operations as well
============================================
Scenario 3 :
When we change the owner of the Contact Relationship, then the owner name will be automatically populated in the Contact Relationship, then the owner name will be automatically populated in the Contact Relationship Name Field.
Trigger :
============================================
trigger ContactRelationshipMasterTrigger on Contact_Relationship__c(before update)
{
if(trigger.isBefore)
{
if(trigger.isUpdate)
{
updateCROwnerName conReload = New UpdateCROwnerName();
conReload.updateCRNameByOwner(trigger.New);
}
}
}
============================================
Apex Class :
============================================
public class updateCROwnerName
{
public void updateCRNameByOwner(List<Contact_Relationship__c > con_rel)
{
Map<Id, String> map_id_Name = new Map<Id,String>();
Set<Id> IdSet = new Set<Id>();
for(Contact_Relationship__c ListRecs : con_rel )
{
IdSet.add(ListRecs.ownerId);
}
List<user> u =[SELECT Id, Name FROM user WHERE Id IN : IdSet];
for(user list_users : u)
{
map_id_Name.put(list_users.Id, list_users.Name);
}
if(u! = null && u.size()>0)
{
for(Contact_Relationship__c ListRecs : con_rel)
{
if(ListRecs.ownerId != null)
{
ListRecs.Name = map_id_Name.get(ListRecs.ownerId);
}
}
}
}
}
============================================
Explanation :
Similar to the second scenario we also called apex class in the trigger.
Let's jump on explanation
Step 1 :
As per the requirement, before performing update operation we have to do some changes in Contact_Relationship__c object. Hence we created a trigger for before update.
Step 2 :
Then we check for a perticular operation to fire the trigger hence we checked whether the event is trigger.isBefore and trigger.isUpdate. Then we simply called the apex class method by creating an instance of a class conReload.
Step 3 :
Inside method, Created a Map with a map_id_Name instance which contains key=Id and value=String as well as Set with IdSet instance which contains Id's set.
Step 4 :
Then in the first for loop, we set the ListRecs.ownerId i.e. ownerId of contact relationship record.
Step 5 :
Then we fetch the users from a query and store its Id and Name in map.
Hence our map now contains userId and userName.
Step 6 :
Then we have null check if a user is there in the list then it will go inside for loop.
Where if Contact_Relationship__c ownerId is not equal to null, then Contact Relationship Name is equal to the name of the user.
These are the real-time scenarios with a simplified breakdown of it.
Please let me know in the comment section if you want more like this 😊
Please let me know in the comment section if you want more like this 😊
WOHOOO !! YOU HAVE JUST COMPLETED SALESFORCE APEX TRIGGER SCENARIOS EPISODE
If you like this salesforcekid learning platform please let me know in the Comment section...Also, Share with your salesforce folks wish you
Happy learning ☁️⚡️ (Learn. Help. Share.)
Salesforce Trigger Scenarios | Simplified
Reviewed by
on
Rating:
In Scenario 1: we can use UserInfo.getName() to update the logged in User to update the Sales rep.
ReplyDeletetrigger UpdateSalesRep on Account (before insert , before Update) {
For(Account Acc: Trigger.New){
Acc.Sales_Rep__c=userInfo.getName();
}}
Hi,
DeleteAs we want user's name who is account owner hence I store account ownerId first and then used that user name further in the trigger.
Hence we have not used this way.
Thanks for understanding
can we use this code to reduce the Time Complexity :-
Deletetrigger AccounyTrigger on Account (after insert) {
if(Trigger.isAfter && Trigger.isInsert){
List accList =[SELECT Id,Owner.name from Account WHERE Id IN: Trigger.new];
for(Account eachAcc : accList)
{
eachAcc.Sales_Rep__c=eachAcc.Owner.name;
}
if(accList!=null && accList.size()>0) UPDATE accList;
}
}
ignore Above comment i written wrong
DeletePlease give more exaamples on Trigger.
ReplyDeleteFor calculate total salary on contact object.
Can you please describe more about scenario ??
Deletein the above second senario i created custom contact object ,when i m matching CR.contact_c=newConts.id here im getting error what would be the reason.plz eplain it
ReplyDeleteyou don't have to create custom contact object, instead as per requirement you have to create contact relationship object and create LOOKUP RELATIONSHIP with STANDARD contact object field.
DeleteI hope this will solve your problem
Thanks.
List conlist=[select ID, LastName from contact where Contact_Relationship__c=true and Id in :trigger.new];
ReplyDeleteit was wrongly pasted. Can we add above query considering the bulkified version .
ReplyDeleteHi Rohit,
DeleteYou can use this query inside the Map abcInstance = Map([SELECT ID, LastName FROM Contact WHERE Contact_Relationship__c=True AND Id IN :trigger.new];)
like this and then use map further.......
Thanks,
AJINKYA DHAS
(Salesforcekid)
Thanks for sharing!This is best for practice. Please share more scenarios on apex and triggers..
ReplyDeletescenario 3 is not working
ReplyDeletecan you please define the second scenario in brief ?
ReplyDeleteBest website so far for Triggers explanation and Scenarios.
ReplyDeletePlease upload more triggers examples like this
better
ReplyDeleteHi, can you write a trigger if phone no on 1 opportunity is updated then it update the same phone number on all the opportunity present on accounts.
ReplyDelete