Salesforce Basics
Saturday, June 10, 2023
Monday, January 31, 2022
Real time scenarios of salesforce Trigger
Before going towards directly to real time senario of trigger lets go through basics of trigger
Trigger
Trigger is piece of code that is executes before and after a record is Inserted / Updated / Deleted from the force.com database
Trigger Context Variables:
- IsInsert:- Returns true if the trigger was fired due to insert operation.
- IsUpdate:- Returns true if the trigger was fired due to update operation.
- IsDelete:- Returns true if the trigger was fired due to delete operation.
- IsBefore:- Returns true if the trigger was fired before record is saved.
- IsAfter:- Returns true if the trigger was fired after record is saved.
- New:- Returns a list of new version of sObject records:.
- Old:- Returns a list of old version of sObject records.
- NewMap:- Returns a map of new version of sObject records. (map is stored in the form of map
). - OldMap:- Returns a map of old version of sObject records. (map is stored in the form of map
). - Size:- Returns a list of new version of sObject records:.
- isExecuting:- Returns true if the current apex code is a trigger.
Scenarios
- create a trigger on account object which will prevent the users in creating duplicate account based on the name
- Create trigger Whenever an Account Name is modified send an email notification to the contact of an account.
- Create trigger on event object to avoid sessions overlap .
- Write trigger to throw error when account is inserted with IsActive(Checkbox) field is True It should always FALSE
-
2 objects Account and Dsignation parent object: Account Child object: Designation Relationship: Lookup(Field name Account__c on Designation object) If an Account has Designation with Title CEO(Field name Title__c) then the Account field "Area__c" cannot be blank.
- trigger on contentversion object which inserts contentdocumentlink to share files specific user whenever a new file is uploaded.
- Trigger on contentversion object which inserts contentdocumentlink to share files specific user whenever a new file is uploaded.
- Write a trigger automatically create the Pricebook entry for each Product record inserted.
Code
trigger AccountDuplicateTrigger on Account (before insert,before update) { listaccountNames=new list (); for(Account accountVar:trigger.new) { accountNames.add(accountVar.name); } list listOfDuplicateAccounts=[select id,name from Account where name in :accountNames]; for(Account account:trigger.new) { if(trigger.isInsert){ if(listOfDuplicateAccounts.size()!=0) { account.addError('Account already exists with this name'); } } if(trigger.isUpdate) { for(Account oldaccount :trigger.old) { if(account.Name!=oldAccount.Name && listOfDuplicateAccounts.size()!=0) { account.addError('Account already exists with this name'); } } } } }
Code
trigger AccountDuplicateTrigger on Account (before insert,before update) { listaccountNames=new list (); for(Account accountVar:trigger.new) { accountNames.add(accountVar.name); } list listOfDuplicateAccounts=[select id,name from Account where name in :accountNames]; for(Account account:trigger.new) { if(trigger.isInsert){ if(listOfDuplicateAccounts.size()!=0) { account.addError('Account already exists with this name'); } } if(trigger.isUpdate) { for(Account oldaccount :trigger.old) { if(account.Name!=oldAccount.Name && listOfDuplicateAccounts.size()!=0) { account.addError('Account already exists with this name'); } } } } }
Code
trigger validateoverlap on Session__c(before insert) { SeteventID = set (); for(Session__c sNew : trigger.new) { //Eent Reference field eventID.add(sNew.Event__c); } List ExistingSessionList = [Select StartDate__c , EndDate__c from Session__c where event__c in : eventID]; for(Session__c sNew : trigger.new) { for(Session__c sOld : ExistingSessionList) { if(sNew.StartDate__c >= sOld.StartDate__c && sNew.StartDate__c <= sOld.EndDate__c) { sNew.addError('Overlap Session'); } } } }
TRIGGER
trigger AccountTriggerToCheckValidation on Account (before insert) { if(trigger.IsInsert && trigger.IsBefore) { AccountTriggerToCheckValidation_handler.checkIsActiveField(trigger.new); } }
CLASS HANDLER
public class AccountTriggerToCheckValidation_handler { public static void checkIsActiveField(ListaccList) { try{ if(accList.size() > 0) { for (Account ac : accList) { if (ac.IsActive__c == true) { ac.addError('This Account cannot be created with IsActive = true.'); } } } } catch(Exception e) { System.debug('The following exception has occurred: ' + e.getMessage()); System.debug('The following Line : ' + e.getLineNumber()); } } }
TRIGGER
trigger demo on Account (after update) { if(trigger.isAfter && trigger.isUpdate ){ system.debug('hello buddy'); demohandler.validationdemo(trigger.old); } }
CLASS HANDLER
public class demohandler { public static void validationdemo(Listacc){ Set idSet = new Set (); for(Account acc1: acc){ idSet.add(acc1.id); } List accList = [Select id, Area__c,(select id, Title__c from Designations__r) from Account where Id IN: idSet]; for(Account act:Designation__c.){ for(Designation__c deg:accList.act){ if(deg.Title__c == 'CEO' && act.Area__c == ''){ act.addError('Area should not be blank'); } } } } }
Code
eed to put a check to verify if ContentDocumentLink records exist before putting it into final list ContentDocumentList. Logic will be like this. trigger ContentVersionTrigger on ContentVersion (after insert) { if(!TriggerRunOnce.hasAlreadyfired()) { Listusers = [select user.id, user.Email, user.FirstName, user.LastName, user.profile.name, user.Username, user.IsActive FROM user, user.profile where user.LastName IN ('***','***') and user.IsActive=true]; Set contentDocumentIdSet = new Set (); for(ContentVersion cv:trigger.new) { if(cv.ContentDocumentId != null) { contentDocumentIdSet.add(cv.ContentDocumentId); } } List lstContentDocumentlink = [SELECT ContentDocumentId, LINKEDENTITYID FROM ContentDocumentLink WHERE ContentDocumentId IN:contentDocumentIdSet]; List ContentDocumentList = new List (); for(ContentVersion cv:trigger.new) { system.debug('at 5 '+cv); if(cv.ContentDocumentId != null && !lstContentDocumentlink.contains(cv.ContentDocumentId)) { for(user u:users){ if(u.Id != cv.OwnerId){ ContentDocumentLink cdl = new ContentDocumentLink(ContentDocumentId=cv.ContentDocumentId,LINKEDENTITYID = u.Id,SHARETYPE='C'); ContentDocumentList.add(cdl); } } } } insert ContentDocumentList; TriggerRunOnce.setAlreadyfired(); } }
Code
trigger ContentVersionTrigger on ContentVersion (after insert) { if(!TriggerRunOnce.hasAlreadyfired()) { Listusers = [select user.id, user.Email, user.FirstName, user.LastName, user.profile.name, user.Username, user.IsActive FROM user, user.profile where user.LastName IN ('***','***') and user.IsActive=true]; Set contentDocumentIdSet = new Set (); for(ContentVersion cv:trigger.new) { if(cv.ContentDocumentId != null) { contentDocumentIdSet.add(cv.ContentDocumentId); } } List lstContentDocumentlink = [SELECT ContentDocumentId, LINKEDENTITYID FROM ContentDocumentLink WHERE ContentDocumentId IN:contentDocumentIdSet]; List ContentDocumentList = new List (); for(ContentVersion cv:trigger.new) { system.debug('at 5 '+cv); if(cv.ContentDocumentId != null && !lstContentDocumentlink.contains(cv.ContentDocumentId)) { for(user u:users){ if(u.Id != cv.OwnerId){ ContentDocumentLink cdl = new ContentDocumentLink(ContentDocumentId=cv.ContentDocumentId,LINKEDENTITYID = u.Id,SHARETYPE='C'); ContentDocumentList.add(cdl); } } } } insert ContentDocumentList; TriggerRunOnce.setAlreadyfired(); } }
Code
trigger createPriceBookEntry on Product2 (after insert) { ListpriceBookEntryList= new List (); String pricebkId= [SELECT id from Pricebook2 where isStandard=true][0].Id; for(Product2 prod: trigger.new){ priceBookEntry priceBkEntry= new priceBookEntry(); priceBkEntry.Product2Id= prod.Id; priceBkEntry.Pricebook2Id= pricebkId; priceBkEntry.IsActive= True; priceBkEntry.UnitPrice= 100; // Dummy Value priceBkEntry.UseStandardPrice= False; //Add more fields as per requirement priceBookEntryList.add(priceBkEntry); } if(priceBookEntryList.size()>0){ insert priceBookEntryList; } }
Subscribe to:
Posts (Atom)