Apex Trigger Solved Scenarios
Apex Trigger Solved Scenarios
Apex Trigger Solved Scenarios
Solved Scenarios
(Improve Your Salesforce Development Skills)
cS
chool
1. Upon Account Creation if Industry is not null and having value as ‘Media’ then
populate Rating as Hot.
Solution:
if(Trigger.isInsert){
if(Trigger.isBefore){
AccountTriggerHandler.updateRating(Trigger.New);
}
}
}
2. Upon Opportunity Creation if Amount is not null and is greater than 100000 then
populate ‘Hot Opportunity’ in description field.
Solution:
if(Trigger.isInsert){
if(Trigger.isBefore){
OpportunityTriggerHandler.updateDesc(Trigger.New);
}
}
}
if(Trigger.isInsert){
if(Trigger.isBefore){
AccountTriggerHandler.updateRating(Trigger.New);
}
}
}
4. Upon Creation of Position (Custom Object) if it is a New Position and Open Date,
Min Pay & Max Pay are not populated then populated them with below values:
a. Open Date = Today’s Date
b. Min Pay = 10000
c. Max Pay = 15000
Solution:
trigger PositionTrigger on Position__c (before insert) {
if(Trigger.isInsert){
if(Trigger.isBefore){
PositionTriggerHandler.populateDateAndPay(Trigger.New);
}
}
}
public class PositionTriggerHandler {
Solution:
trigger AccountTrigger on Account (after insert) {
if(Trigger.isInsert){
if(Trigger.isAfter){
AccountTriggerHandler.createContact(Trigger.New);
}
}
}
Solution:
trigger AccountTrigger on Account (after insert) {
if(Trigger.isInsert){
if(Trigger.isAfter){
AccountTriggerHandler.createRelatedOpp(Trigger.New);
}
}
}
7. When a Case is created on any Account, put the latest case number on the
Account in the ‘Latest Case Number’ field.
Solution:
trigger CaseTrigger on Case (after insert) {
if(Trigger.isInsert){
if(Trigger.isAfter){
CaseTriggerHandler.populateLatestCaseNum(Trigger.New);
}
}
}
if(Trigger.isInsert){
if(Trigger.isAfter){
OpportunityTriggerHandler.populateAmount(Trigger.New);
}
}
}
Solution:
trigger AccountTrigger on Account (after insert) {
if(Trigger.isInsert){
if(Trigger.isAfter){
AccountTriggerHandler.createContactOrOpp(Trigger.New);
}
}
}
if(oppList.size()>0){
insert oppList;
}
if(conList.size()>0){
insert conList;
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
Solution:
trigger AccountTrigger on Account (before update) {
if(Trigger.isUpdate){
if(Trigger.isBefore){
AccountTriggerHandler.updateDescription(Trigger.New,
Trigger.oldMap);
}
}
}
Solution:
trigger AccountTrigger on Account (before update) {
if(Trigger.isUpdate){
if(Trigger.isBefore){
AccountTriggerHandler.copyBillToShip(Trigger.New,
Trigger.oldMap);
}
}
}
public class AccountTriggerHandler {
public static void copyBillToShip(List<Account> accList,Map<Id,Account>
oldMap){
for(Account acc:accList){
if((oldMap==null && acc.CopyBillingToShipping__c) ||
(!oldMap.get(acc.Id).CopyBillingToShipping__c &&
acc.CopyBillingToShipping__c)){
acc.ShippingCity=acc.BillingCity;
acc.ShippingCountry=acc.BillingCountry;
acc.ShippingPostalCode=acc.BillingPostalCode;
acc.ShippingState=acc.BillingState;
acc.ShippingStreet=acc.BillingStreet;
}
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
12. Upon Account Creation or updation if Industry is not null and having value
as ‘Media’ then populate Rating as Hot.
Solution:
trigger AccountTrigger on Account (before update) {
if(Trigger.isUpdate){
if(Trigger.isBefore){
AccountTriggerHandler.updateIndustryRating(Trigger.New,
Trigger.oldMap);
}
}
}
public class AccountTriggerHandler {
13. If opportunity Stage is updated upon its creation or update then update
description as either 'Opp is Closed Lost' or 'Opp is Closed Won' or 'Opp is
Open'.
Solution:
trigger OpportunityTrigger on Opportunity (before update) {
if(Trigger.isUpdate){
if(Trigger.isBefore){
OpportunityTriggerHandler.updateDesc(Trigger.New,
Trigger.oldMap);
}
}
}
public class OpportunityTriggerHandler {
public static void updateDesc(List<Opportunity>
oppList,Map<Id,Opportunity> oldMap){
for(Opportunity opp:oppList){
if((oldMap==null)||(opp.StageName!=oldMap.get(opp.Id).Stage
Name)){
if(opp.StageName=='Closed Won'){
opp.Description='Opportunity is Closed won';
}else if(opp.StageName=='Closed Lost'){
opp.Description='Opportunity is closed lost';
}else{
opp.Description='Opportunity is open';
}
}
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
14. If the Account phone is updated then populate the phone number on all
related Contacts (Home Phone field). [Using Map]
Solution:
trigger AccountTrigger on Account (after update) {
if(Trigger.isUpdate){
if(Trigger.isAfter){
AccountTriggerHandler.updateRelatedConts(Trigger.New,
Trigger.oldMap);
}
}
}
public class AccountTriggerHandler {
public static void updateRelatedConts(List<Account>
accList,Map<Id,Account> oldMap){
List<Contact> conList=new List<Contact>();
Map<Id,Account> accToAccountMap= new Map<Id,Account>();
for(Account acc:accList){
if((acc.Phone!=null && acc.Phone!=(oldMap.get(acc.Id).Phone))
&& oldMap!=null){
accToAccountMap.put(acc.Id,acc);
}
}
conList.add(cont);
}
}
if(!conList.isEmpty()){
update conList;
}
OR
if(conList.size() > 0){
update conList;
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
15. If the Account phone is updated then populate the phone number on all
related Contacts (Home Phone field). [Using Parent-Child SOQL]
Solution:
trigger AccountTrigger on Account (after update) {
if(Trigger.isUpdate){
if(Trigger.isAfter){
AccountTriggerHandler.updateRelatedConts(Trigger.New,
Trigger.oldMap);
}
}
}
public class AccountTriggerHandler {
conList.add(con);
}
}
}
if(!conList.isEmpty()){
update conList;
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
16. If the Account billing address is updated then update related contacts
mailing address. [Using Map]
Solution:
trigger AccountTrigger on Account (after update) {
if(Trigger.isUpdate){
if(Trigger.isAfter){
AccountTriggerHandler.updateRelatedConts(Trigger.New,
Trigger.oldMap);
}
}
}
public class AccountTriggerHandler {
public static void updateRelatedContactMail(List<Account>
accList,Map<Id,Account> oldMap){
List<Contact> conList=new List<Contact>();
Map<Id,Account> accToAccountMap= new Map<Id,Account>();
for(Account acc:accList){
if( (!acc.BillingCity.equals(oldMap.get(acc.Id).BillingCity) ||
!acc.BillingCountry.equals(oldMap.get(acc.Id).BillingCountry) ||
!acc.BillingPostalCode.equals(oldMap.get(acc.Id).BillingPostalC
ode) ||c!acc.BillingState.equals(oldMap.get(acc.Id).BillingState)
|| !acc.BillingStreet.equals(oldMap.get(acc.Id).BillingStreet) )
&& oldMap!=null){
accToAccountMap.put(acc.Id,acc);
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
if(accToAccountMap.containsKey(cont.AccountId)){
con.MailingCountry =
accToAccountMap.get(cont.AccountId).BillingCountry;
con.MailingCity =
accToAccountMap.get(cont.AccountId).BillingCity;
con.MailingState =
accToAccountMap.get(cont.AccountId).BillingState;
con.MailingPostalCode =
accToAccountMap.get(cont.AccountId).BillingPostalCode;
con.MailingStreet =
accToAccountMap.get(cont.AccountId).BillingStreet;
conList.add(con);
}
}
if(!conList.isEmpty()){
update conList;
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
17. If the Account billing address is updated then update related contacts
mailing address. [Using Parent-Child SOQL]
Solution:
trigger AccountTrigger on Account (after update) {
if(Trigger.isUpdate){
if(Trigger.isAfter){
AccountTriggerHandler.updateRelatedConts(Trigger.New,
Trigger.oldMap);
}
}
}
public class AccountTriggerHandler {
if(acc.Contacts!=null){
for(Contact cont:acc.Contacts){
cont.MailingCountry=acc.BillingCountry;
cont.MailingCity= acc.BillingCity;
cont.MailingState=acc.BillingState;
cont.MailingPostalCode=acc.BillingPostalCode;
cont.MailingStreet=acc.BillingStreet;
conList.add(cont);
}
}
}
if(!conList.isEmpty()){
update conList;
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
19. Write a trigger on Account when Account Active field is updated from ‘Yes’
to ‘No’ then check all opportunities associated with the account. Update all
Opportunities Stage to close lost if stage not equal to close won.
Solution:
trigger AccountTrigger on Account (after update) {
if(Trigger.isUpdate){
if(Trigger.isAfter){
AccountTriggerHandler.updateOpportunityStage(Trigger.New,
Trigger.oldMap);
}
}
}
public class AccountTriggerHandler {
if(opp.StageName!='Closed
Won'&&opp.StageName!='Closed Lost'){
opp.StageName='Closed Lost';
oppList.add(opp);
}
}
}
}
if(oppList.size( ) > 0){
update oppList;
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
Solution:
trigger AccountTrigger on Account (before delete) {
if(Trigger.isDelete){
if(Trigger.isBefore){
AccountTriggerHandle.preventDel(Trigger.old);
}
}
}
21. Prevent account record from being edited if the record is created 7 days
back.
Solution:
trigger AccountTrigger on Account (before update) {
if(Trigger.isUpdate){
if(Trigger.isBefore){
AccountTriggerHandle.preventAccEdit(Trigger.new);
}
}
}
Solution:
trigger OpportunityTrigger on Opportunity (before insert) {
if(Trigger.isInsert){
if(Trigger.isBefore){
OpportunityTriggerHandler.validateAmount(Trigger.New);
}
}
}
public class OpportunityTriggerHandler {
23. When an opportunity is updated to Closed Lost and Closed Lost Reason
(field) is not populated then throw validation error that ‘Please populate
Closed Lost Reason’ on opportunity. [before update]
Solution:
24. Write a trigger on Account and check only System Administrator profile
users should be able to delete an account.
Solution:
Solution:
trigger OpportunityTrigger on Opportunity (before delete) {
if(Trigger.isDelete){
if(Trigger.isBefore){
OpportunityTriggerHandler.checkProfileForDeletion(Trigger.old);
}
}
}
public class OpportunityTriggerHandler {
for(Account acc:accList){
idSet.add(acc.Id);
}
for(Account acc:[SELECT Id,(SELECT Id FROM Opportunities)FROM
Account WHERE Id IN:idSet]){
if(acc.Opportunities.size( ) > 0){
acc.addError('You can not delete account where
opportunities are available ');
}
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
27. Prevent deletion of an account if there is any case related to that account.
Solution:
trigger AccountTrigger on Account (before delete) {
if(Trigger.isDelete){
if(Trigger.isBefore){
AccountTriggerHandler.preventDelIfHasRelatedOpp(Trigger.old);
}
}
}
for(Account acc:accList){
idSet.add(acc.Id);
}
for(Account acc:[SELECT Id,(SELECT Id FROM Cases)FROM Account
WHERE Id IN:idSet]){
if(acc.Cases.size() > 0){
acc.addError('You can not delete account where cases are
available ');
}
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
28. When the Employee record is deleted then update ‘Left Employee Count’
on Account.
Solution:
trigger EmployeeTrigger on Employee__c (After delete) {
if(Trigger.isDelete){
if(Trigger.isAfter){
EmployeeTriggerHandler.leftEmpCount(Trigger.old);
}
}
}
for(Employee__c emp:oldEmpList){
if(emp.Account__c!=null){
accIds.add(emp.Account__c);
empList.add(emp);
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
if(!accIds.isEmpty()){
accIdToAccMap= new Map<Id,Account>([SELECT
Id,Left_Employee_Count__c FROM Account WHERE Id
IN:accIds]);
}
if(!empList.isEmpty()){
for(Employee__c emp:empList){
if(accIdToAccMap.containsKey(emp.Account__c)){
if(accIdToTotalCount.containsKey(emp.Account__c)){
Decimal count =
accIdToTotalCount.get(emp.Account__c)+1;
accIdToTotalCount.put(emp.Account__c,count);
}else{
accIdToTotalCount.put(emp.Account__c,accIdToAcc
Map.get(emp.Account__c).Left_Employee_Count__c+1);
}
}
}
}
for(Id accId:accIdToTotalCount.keySet()){
Account acc= new Account();
acc.Id=accId;
acc.Left_Employee_Count__c=accIdToTotalCount.get(accId);
accToBeUpdated.add(acc);
}
if(!accToBeUpdated.isEmpty()){
update accToBeUpdated;
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
30. When the Employee record is undeleted then update ‘Left Employee Count’
on Account.
Solution:
trigger EmployeeTrigger on Employee__c (After undelete) {
if(Trigger.isUnDelete){
if(Trigger.isAfter){
EmployeeTriggerHandler.updateLeftEmpCountUndeletedOnes(Trigger.New);
}
}
}
for(Employee__c emp:oldEmpList){
if(emp.Account__c!=null){
accIds.add(emp.Account__c);
empList.add(emp);
}
}
if(!accIds.isEmpty()){
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
accIdToTotalCount.put(emp.Account__c,accIdToAccMap.get(emp.Account__c).L
eft_Employee_Count__c-1);
}
}
}
}
for(Id accId:accIdToTotalCount.keySet()){
31. When the Employee record is inserted, deleted and undeleted then update
‘Present Employee Count’ on related Account. [Parent-Child SOQL]
Solution:
//Same code will work for insert, delete and undelete
trigger EmployeeTrigger on Employee__c(after insert,after delete,after undelete) {
if(Trigger.isInsert){
if(Trigger.isAfter){
EmployeeTriggerHandler.updatePresentEmpCount(Trigger.New);
}
}
if(Trigger.isDelete){
if(Trigger.isAfter){
EmployeeTriggerHandler.updatePresentEmpCount(Trigger.New);
}
}
if(Trigger.isUnDelete){
if(Trigger.isAfter){
EmployeeTriggerHandler.updatePresentEmpCount(Trigger.New);
}
}
}
idSet.add(emp.Account__c);
}
}
if(!accList.isEmpty()){
update accList;
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
}
Messaging.sendEmail(emailList);
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
33. Create two record types named as “Partner Case” and “Customer Case” on
Case Object. On creation of Case, as per the record type populate the total
number of Partner Case or Customer Case on Account object. Create
Custom Fields on Account to have total numbers.
Solution:
trigger CaseTrigger on Case (after insert) {
if(Trigger.isInsert){
if(Trigger.isAfter){
CaseTriggerHandler.countCases(Trigger.new);
}
}
}
public class CaseTriggerHandler{
public static void countCases(List<Case> cList){
List<Account> accList= new List<Account>();
Set<Id> idSet= new Set<Id>();
Id partnerCaseRecordTypeId = [Select Id From RecordType Where
DeveloperName = 'Partner_Case'].Id;//1.way to do with
DeveloperName which is API name
Id customerCaseRecordTypeId=[Select Id From RecordType Where
Name = 'Customer Case'].Id;//2.way to do with Name
for(Case c:cList){
if(c.AccountId!=null){
idSet.add(c.AccountId);
}
}
for(Account acc:[SELECT
Id,Total_Case__c,Customer_Case__c,Partner_Case__c,(SELE
CT Id,RecordTypeId FROM Cases) FROM Account WHERE Id
IN:idSet]){
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
decimal countPartner=0;
decimal countCustomer=0;
for(Case c:acc.Cases){
if(c.RecordTypeId==partnerCaseRecordTypeId){
countPartner++;
}else if(c.RecordTypeId==customerCaseRecordTypeId){
countCustomer++;
}
}
acc.Customer_Case__c=countCustomer;
acc.Partner_Case__c=countPartner;
acc.Total_Case__c=acc.Customer_Case__c+acc.Partner_Case
__c;
accList.add(acc);
}
if(!accList.isEmpty()){
update accList;
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
acc.AnnualRevenue=total;
}
}
if(!accList.isEmpty()){
update accList;
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
Solution:
trigger AccountTrigger on Account (after insert) {
if(Trigger.isInsert){
if(Trigger.isAfter){
AccountTriggerHandler.createOpp(Trigger.new);
}
}
}
}
accList[i].addError(errors);
}
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
37. When an opportunity is updated to closed won or closed lost then update
description having value 'Opportunity is Closed Won' or 'Opportunity is
Closed Lost' accordingly. (Hint: Recursion)
Solution:
if(opp.StageName=='Closed Won'){
o.Description='Opportunity is Closed Won';
}else if(opp.StageName=='Closed Lost'){
o.Description='Opportunity is Closed Lost';
}
oppToBeUpdated.add(o);
}
}
if(!oppToBeUpdated.isEmpty()){
update oppToBeUpdated;
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
38. Write a trigger, if the owner of an account is changed then the owner for the
related contacts should also be updated. [Without Map]
Solution:
trigger AccountTrigger on Account (after update) {
if(Trigger.isUpdate){
if(Trigger.isAfter){
AccountTriggerHandler.updateOwnerOfRelatedContact(Trigger.
new, Trigger.oldMap);
}
}
}
}
}
}
if(!conList.isEmpty()){
update conList;
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
39. Write a trigger, if the owner of an account is changed then the owner for the
related contacts should also be updated. [Using Map]
Solution:
trigger AccountTrigger on Account (after update) {
if(Trigger.isUpdate){
if(Trigger.isAfter){
AccountTriggerHandler.updateOwnerOfRelatedContact(Trigger.
new, Trigger.oldMap);
}
}
}
if(!conList.isEmpty()){
update conList;
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
40. Whenever a new User having profile “System Administrator” is inserted and
is Active, add the user to the public group “Admins”. Create a public group
named Admins.
Solution:
trigger UserTrigger on User (after insert) {
if(Trigger.isInsert){
if(Trigger.isAfter){
UserTriggerHandler.addUserToGroup(Trigger.new);
}
}
}
for(User us : usList){
if(us.ProfileId == systemAdminId && us.IsActive){
GroupMember grp= new GroupMember();
grp.GroupId=groupId;
grp.UserOrGroupId=us.Id;
groupList.add(grp);
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
if(!groupList.isEmpty()){
insert groupList;
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
42. Set OWD as Private for Account. Once an Account record is created, it
should be automatically shared with any one user who belongs to Standard
User profile.
Solution:
trigger AccountTrigger on Account (after insert) {
if(Trigger.isInsert){
if(Trigger.isAfter){
AccountTriggerHandler.shareAccWithStdUser(Trigger.new);
}
}
}
for(Account acc:accList){
AccountShare aShare= new AccountShare();
aShare.UserOrGroupId=listOfUserId[0].Id;
aShare.AccountId=acc.Id;
aShare.RowCause='Manual';
aShare.AccountAccessLevel='Edit';
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
aShare.OpportunityAccessLevel='Edit';
accShareList.add(aShare);
}
if(!accShareList.isEmpty()){
insert accShareList;
}
}
}
Sanjay Gupta Tech School
Join Free & Live Salesforce Admin & Dev Bootcamp on Youtube
if(Trigger.isExecuting){
//do whatever you want to do as part of the trigger invocation
}
else{
//do whatever you want to do if the call originated from a
different context, such as from the controller.
}
return Trigger.isExecuting;
}
}
Note:
● If you find any bug in any of the code snippets then please share in
the comments.
● A problem can be solved through more than one way. If you know any
other way then please share it as well in comments