0% found this document useful (0 votes)
22 views

40 Apex Trigger Scenario Use Cases with Solution

The document outlines 40 scenarios and use cases for Apex triggers in Salesforce development, aimed at automating business processes and enhancing workflow efficiency. It provides practical solutions and code examples for various situations, such as automatically creating related records, updating fields based on specific conditions, and preventing duplicate entries. The triggers are designed to address complex business requirements while ensuring data integrity and compliance with business rules.

Uploaded by

Farheen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

40 Apex Trigger Scenario Use Cases with Solution

The document outlines 40 scenarios and use cases for Apex triggers in Salesforce development, aimed at automating business processes and enhancing workflow efficiency. It provides practical solutions and code examples for various situations, such as automatically creating related records, updating fields based on specific conditions, and preventing duplicate entries. The triggers are designed to address complex business requirements while ensuring data integrity and compliance with business rules.

Uploaded by

Farheen
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

40 APEX TRIGGER

SCENARIO/USE CASES
WITH SOLUTION

@salesforcecorporatetrainer
Apex triggers are essential components of
Salesforce development, allowing
developers to automate business
processes and execute custom logic.
However, writing effective Apex triggers
can be challenging, particularly when
dealing with complex business
requirements.
In this post, we will explore 40 common
scenarios and use cases where Apex
triggers can be used to automate
business processes and streamline
workflow. We will provide practical
solutions and code examples to help
developers build robust and efficient
triggers.

@salesforcecorporatetrainer
When ever a record is
inserted to the account
automatically inserted
to the contact

@salesforcecorporatetrainer
@salesforcecorporatetrainer
When ever a record is
inserted to the contact
automatically inserted
to the account

@salesforcecorporatetrainer
@salesforcecorporatetrainer
When ever a create
opportunity object
record updated total
opportunies and total
amount in account
object

@salesforcecorporatetrainer
trigger scenario24 on Opportunity (after insert) {
set<id>ids = new set<id>();
for(Opportunity op : trigger.new) {
ids.add(op.accountid);
}
list<account> ac = [select Total_opportunities__c,
Total_Amount__c, (select id, Amount from
Opportunities) from account where id = :ids];
for(account a : ac) {
a.Total_opportunities__c = a.opportunities.size();
decimal sum = 0;
for(opportunity p : a.opportunities) {
sum = sum + p.amount;
}
a.Total_Amount__c = sum;
}
update ac;
}

@salesforcecorporatetrainer
Contact object when
ever department
equal to cse
automatically before
inserted email field

@salesforcecorporatetrainer
@salesforcecorporatetrainer
When ever we modify
inputout object
doctorname
automatically update
droppoff object text
field no relation ship

@salesforcecorporatetrainer
trigger SCENARIO32 on Inputout__c (after update) {
list<Dropoff1__c> d = [SELECT Id, Name, Text__c
FROM Dropoff1__c WHERE Text__c = 'naveen']; string name; for
(Inputout__c c : trigger.new) { name = c.Doctor_Name__c; } for
(Dropoff1__c dp : d) { dp.Text__c = name; } update d; }

@salesforcecorporatetrainer
Limit reached the
records

@salesforcecorporatetrainer
trigger SCENARIO6 on Account (before insert,before update) {
integer count=0;
list<account> a = [select id,name from account where
createddate=today or lastmodifieddate=today];
for(account ac: trigger.new) {
count = a.size();
ac.NumberofLocations__c = count;
if(count > 2) {
ac.addError('Reached limit today');
}
}
}

@salesforcecorporatetrainer
Can not
inser/update/delete
that user account
object records

@salesforcecorporatetrainer
@salesforcecorporatetrainer
Already existing
records display error
message

@salesforcecorporatetrainer
trigger scenario8 on Contact (before insert) {

list<string>st=new list<string>();

for(contact c:trigger.new) {

list<contact>a=[select id,name,Email,lastname from contact


where Email=:c.Email];

if(a.size()>0) {

c.Email.adderror('already existing');

}
}

@salesforcecorporatetrainer
Count of related
contacts and
accounts field display
size

@salesforcecorporatetrainer
public static void increment(list<contact>con) {
set<id>ids=new set<id>();

for(contact c:con) {
ids.add(c.accountid);
}

list<account>a=[select id,name,NumberOfEmployees,(select
id,lastname from contacts) from account where id=:ids];

for(account ac:a) {
ac.NumberOfEmployees=ac.contacts.size();
}

update a;
}

@salesforcecorporatetrainer
when ever opportunity
stagename
=closedwon
automatically update
the account field
rating=hot

@salesforcecorporatetrainer
@salesforcecorporatetrainer
when ever account
name is naveen
automatically update
the contact all
lastnames

@salesforcecorporatetrainer
trigger scenario13 on Account (after update) {
string names;
list<contact> c = [select id, lastname, firstname from contact
where lastname = :names];

for(account a : trigger.new) {
names = a.Name;
}

for(contact con : c) {
con.LastName = names;
}

update c;
}

@salesforcecorporatetrainer
when ever a opportunity
created record amount
field is calculated by
account total field

@salesforcecorporatetrainer
trigger scenario21 on Opportunity (after insert, after update, after
delete) { set<id> ids = new set<id>(); map<id, opportunity> opp =
new map<id, opportunity>(); Decimal oldVal; Decimal newVal;

if(trigger.isInsert) { for(opportunity op : trigger.new) {


ids.add(op.AccountId); opp.put(op.AccountId, op); } list<account>
acc = [select id, Total_Amount__c from account where id = :ids];
for(account a : acc) { if(a.Total_Amount__c == null) {
a.Total_Amount__c = opp.get(a.Id).Amount; }

@salesforcecorporatetrainer
} else { a.Total_Amount__c += opp.get(a.Id).Amount; } } update
acc; } else if(trigger.isUpdate) { for(opportunity op : trigger.new) {
if(op.Amount != trigger.oldMap.get(op.Id).Amount) {
ids.add(op.AccountId); opp.put(op.AccountId, op); } }
list<account> acc = [select id, Total_Amount__c from account
where id = :ids]; for(account a : acc) {
list<account> acc = [select id, Total_Amount__c from account
where id = :ids]; for(account a : acc) { oldVal =
trigger.oldMap.get(a.Id).Total_Amount__c; newVal =
a.Total_Amount__c; if(oldVal == null) { oldVal = 0; } if(newVal ==
null) { newVal = 0; } a.Total_Amount__c = (newVal - oldVal) +
opp.get(a.Id).Amount; } update acc; } else if(trigger.isDelete) {
for(opportunity op : trigger.old) { ids.add(op.AccountId);
opp.put(op.AccountId, op);

@salesforcecorporatetrainer
} list<account> acc = [select id, Total_Amount__c from account
where id = :ids];
for(account a : acc) { if(a.Total_Amount__c != null) {
a.Total_Amount__c -= opp.get(a.Id).Amount; } } update acc; } }

@salesforcecorporatetrainer
when ever a create a
lead object
automatically
converted account
,contact,opportunity

@salesforcecorporatetrainer
@salesforcecorporatetrainer
when ever create a
contact automatically
update opprtunity fields

@salesforcecorporatetrainer
@salesforcecorporatetrainer
Whenever new account
is created, its rating
should be hot.

@salesforcecorporatetrainer
@salesforcecorporatetrainer
Make a Fax field
mandatory in Account
using trigger.

@salesforcecorporatetrainer
@salesforcecorporatetrainer
Whenever a new
contact is created,
prefix the firstname with
Mr.

@salesforcecorporatetrainer
@salesforcecorporatetrainer
Prevent the insertion of
an account, if you
already have an
account with the same
name

@salesforcecorporatetrainer
Set<String> setName = new Set<String>(); for(Account acc :
trigger.new) { setName.add(acc.name); } if(setName.size() > 0 ) {
List<Account> lstAccount = [SELECT name, id FROM Account
WHERE name IN :setName]; Map<String ,Account>
mapNameWiseAccount = new Map<String,Account>();
for(Account acc: lstAccount) {
mapNameWiseAccount.put(acc.name ,acc); } for(Account acc :
trigger.new) { if(mapNameWiseAccount.containsKey(acc.name)) {
acc.Name.addError('Name already exists'); } } } }

@salesforcecorporatetrainer
Whenever a new
contact is inserted in
the system, update the
accounts phone field
with the contacts phone
field

@salesforcecorporatetrainer
trigger contactTrigger on Contact (before insert, before update,
before delete, after insert, after update, after delete, after
undelete) {

if(trigger.isBefore){
system.debug('I am before trigger ');
}
else if(trigger.isAfter){
system.debug('I am after trigger ');
if(trigger.isUpdate){
contactTriggerHandler.afterUpdateHelper(trigger.new);
}
}
}

@salesforcecorporatetrainer
Create a contact
whenever a new
account is created.

@salesforcecorporatetrainer
@salesforcecorporatetrainer
Prevent to delete
account if they have
related opportunity

@salesforcecorporatetrainer
trigger DeleteAccountOpportunity1 on Account (before delete) {

List<Opportunity> opp = [Select accountID from opportunity


where accountid in :TRIGGER.OLD];

for(Account a : Trigger.OLD) {

for(Opportunity o : Opp) {

if(a.id == o.accountId) {

a.addError('Account has Opportunity, so you cannot


delete this Account');

@salesforcecorporatetrainer
if the account does not
exist during the creation
of a record in the
contact object then
create a new account
record

@salesforcecorporatetrainer
NEEDS TO ASK

@salesforcecorporatetrainer
Trigger will prevent the
user to delete records
from account

@salesforcecorporatetrainer
trigger test6 on Account (before delete) {

for (Account A:Trigger.old){


A.addError(' You can not delete the record, Please contact your
Administartator');
}

@salesforcecorporatetrainer
Prevent user from
creating duplicate
accounts with same
name

@salesforcecorporatetrainer
trigger AccountDuplicate on Account (before insert) {

Set<String> setName = new Set<String>();

for(Account acc : trigger.new) {


setName.add(acc.name);
}

if(setName.size() > 0 ) {

List<Account> lstAccount = [select name ,id from account where


name in :setName ];

Map<String ,Account> mapNameWiseAccount = new


Map<String,Account>();

for(Account acc: lstAccount) {


mapNameWiseAccount.put(acc.name ,acc);
}

for(Account acc : trigger.new) {


if(mapNameWiseAccount.containsKey(acc.name)) {
acc.Name.addError('Name already Exist ');
}
}
}
}

@salesforcecorporatetrainer
Add a prefix dr to all
leads names whenever
a record is updated or
inserted

@salesforcecorporatetrainer
Set<Id> accountIds = new Set<Id>();
List<Contact> newContacts = Trigger.new;

for (Contact newContact : newContacts) {


accountIds.add(newContact.AccountId);
}

List<Account> accountsToUpdate = [SELECT Id, Status__c, (SELECT


Id FROM Contacts) FROM Account WHERE Id IN :accountIds];

for (Account accountToUpdate : accountsToUpdate) {


accountToUpdate.Status__c = 'Active';
for (Contact accountContact : accountToUpdate.Contacts) {
if (accountContact.Id != null) {
accountToUpdate.Status__c = 'Active with Contact';
break;
}
}
}

update accountsToUpdate;

@salesforcecorporatetrainer
Prevent user to delete
contact which is
associated with any
account.

@salesforcecorporatetrainer
for (Contact c : Trigger.old) {
if (c.AccountId != null) {
c.addError('Cannot delete contact associated with an
Account.');
}
}

@salesforcecorporatetrainer
Throw an error if phone
number is not 10 dight
of length

@salesforcecorporatetrainer
@salesforcecorporatetrainer
Whenever contact is
created update status
field from it's associate
account

@salesforcecorporatetrainer
Keep Reading!

@salesforcecorporatetrainer
Whenever a new record
is created in account
object, before this
record inserted in
account object Account

@salesforcecorporatetrainer
Delete all contact
records available with
the same name

@salesforcecorporatetrainer
When ever a record is
inserted to the Account
automatically inserted
to the Contact

@salesforcecorporatetrainer
trigger SCENARIO1 on Account (after insert) {
list<contact> c=new list<contact>();
for(account a:trigger.new)
{
contact b = new contact();
b.LastName = a.Name;
b.AccountId = a.Id;
c.add(b);
}
insert c;

@salesforcecorporatetrainer
when ever a create
opportunity object
record updated total
opportunies and total
amount in account
object

@salesforcecorporatetrainer
trigger scenario24 on Opportunity (after insert) {
set<id> ids = new set<id>();
for(Opportunity op:trigger.new)
{
ids.add(op.accountid);
}
list<account>ac=[select
Total_opportunities__c,Total_Amount__c,(select id,Amount
from Opportunities ) fro
ma
ccount where id=:ids];
for(account a:ac)
{
a.Total_opportunities__c=a.opportunities.size();
decimal sum=0;
for(opportunity p:a.opportunities)
{
sum=sum+p.amount;
}
a.Total_Amount__c=sum;

}
update ac;
}

@salesforcecorporatetrainer
Can not
inser/update/delete
that user account
object records

@salesforcecorporatetrainer
trigger AccountDuplicate on Account (before insert, before
update, before delete){

for (Account a:Trigger.new){


a.addError('Need to contact Amin for access');
}
}

@salesforcecorporatetrainer
when ever opportunity
stagename
=closedwon
automatically update
the account field
rating=hot

@salesforcecorporatetrainer
trigger updateAccountRating on opportunity (after insert, after update){
list<Id> accIds = new list<Id>();
list<Account> accounts = new list<account>();
for(opportunity o:trigger.new){
accIds.add(o.accountId);
}
for(account a:[select Id, Rating from account where Id IN :accIds]){
for(opportunity opp:trigger.new){
if(opp.stage=='closed won'){
a.Rating='hot';
accounts.add(a);
}
}
}
update accounts;
}

@salesforcecorporatetrainer
name field is updated
on account then put
name field as name +
Phone

@salesforcecorporatetrainer
trigger AccountDuplicate on Account (before update){

for (Account a:Trigger.new){


if (a.name != Trigger.oldMap.get(a.Id).name){
a.name = a.name + trigger.oldMap.get(a.id).phone;
}
}
}

@salesforcecorporatetrainer
Whenever account is
created with annual
revenue more than
50000, then add Pranay
mehare as contact
Name

@salesforcecorporatetrainer
DONE (Check 50 k and insert contact )

trigger test5 on Account (before insert) {

list<Contact> ContList = new List<Contact>();


// set<Id> AccIdsSet = new Set<Id>();

for (Account Acc:Trigger.new){

if (Acc.AnnualRevenue > 50000){


Contact cont = new contact();

Cont.AccountId = Acc.Id;
Cont.Firstname = 'Pranay';
Cont.Lastname = 'Mehare';
ContList.add(Cont);
}
}
Insert ContList;

@salesforcecorporatetrainer
Whenever Lead is
created with lead
Source as WEB then
give rating as COLD
otherwise HOT

@salesforcecorporatetrainer
trigger test56 on Lead (before insert) {

for (Lead l:Trigger.New){

if (l.leadSource == 'Web'){
l.Rating = 'Cold';
}
Else{
l.Rating = 'Hot';
}
}
}

@salesforcecorporatetrainer
Prevent Account from
deleting if it has 2 or
more contacts

@salesforcecorporatetrainer
trigger Account1 on Account (before Delete) {

set<Id> AccIds = new set<Id>();


Map<Id, Account> AccMap = new Map<Id, Account>(); // need to store
map

for (Account A:Trigger.old){

AccIds.add(A.Id);
}
for (Account A:[SELECT Id, Name, (SELECT Id, Firstname, LastName FROM
Contacts) FROM ACCOU
NT WHERE Id IN :AccIds]){
AccMap.put(A.Id, A);
}
for (Account A1:Trigger.Old){

if (AccMap.get(A1.id).contacts.Size() >= 2){


A1.addError('You Can not delete Account');
}
}

@salesforcecorporatetrainer
While creating or
updating Lead check
whether Email is
already there in existing
contact , if it is there
then throw an error

@salesforcecorporatetrainer
//Unrelated Objects ::

trigger Lead1 on Lead (before insert, before update) {


map<string, contact> contMap = new map<string, contact>();
list<contact> contEmail = [SELECT Id, Email FROM Contact];

for (contact c:contEmail){

contMap.put(c.Email, c);
}
for (lead l:Trigger.new){

if ((l.email != null) && (trigger.isInsert || (l.email !=


Trigger.oldMap.get(l.Id).Email))){
if (contMap.containsKey(l.email)){
l.Email.addError('Email already exist');
}
}
}
}

@salesforcecorporatetrainer
Whenever phone is
modified on account
object then update
contact record with
phone field

@salesforcecorporatetrainer
trigger updatePhone on Account (after update) {

Set<Id> accIdSet = new Set<Id>();


for(Account acc : Trigger.New){
if(acc.Phone!=trigger.oldmap.get(acc.Id).Phone){
accIdSet.add(acc.Id);
}
}
list<contact> conlist = new list<contact>();
for(Contact con : [select Id,AccountId from Contact Where
AccountId In : accIdSet]){

con.HomePhone=trigger.newmap.get(con.AccountId).Phone;
con.OtherPhone = trigger.oldmap.get(con.AccountId).Phone;
conlist.add(con);
}
update conlist;

@salesforcecorporatetrainer
Counts number of
contacts on Account
using trigger (Create
Lookup Summary field
using Trigger)

@salesforcecorporatetrainer
Note : Object CONTACT [Very importatnt]

TRIGGER :

trigger ContCount on Contact (After Delete, After Insert, After


Update, After Undelete) {

If (Trigger.isInsert || Trigger.isDelete || Trigger.isUpdate ||


Trigger.isUndelete){

CountContact.ContContacts (Trigger.New, Trigger.Old);


}
}

HANDLER CLASS :

Public class CountContact {


Public static void ContContacts (list<Contact> NewContact,
List<Contact> oldContact){

set<id> ContAccIds = new set<Id>();

try{
if (NewContact != Null){
for (Contact con:newContact){
if(Con.AccountId != Null){
ContAcc
}
@salesforcecorporatetrainer
if (oldContact != Null){
for (Contact con:oldContact){
if(Con.AccountId != Null){
ContAccIds.add(con.AccountId);
}
}
}

List<Account> AccList = [SELECT Id, ContCount__c, (SELECT Id FROM


Contacts) FROM Accoun
t Where Id IN :ContAccIds];

if (AccList != Null){
for (Account AccValue:AccList){
accvalue.ContCount__c = accValue.Contacts.Size();
}
}

if(!AccList.isEmpty()){
update AccList;
}
}

Catch (Exception e){


System.debug ('Get Message' + e.getMessage());
}
}
}
@salesforcecorporatetrainer
Conclusion
These scenarios cover a wide range of
objects and business requirements and can
be used as a reference guide for developers
and administrators to implement the
corresponding trigger logic. Overall, this
carousel offers a useful resource for anyone
looking to learn more about Apex Triggers in
Salesforce and how they can be utilized to
automate business processes and maintain
data integrity.

@salesforcecorporatetrainer
Continuously exploring and implementing
new techniques can greatly enhance
your productivity and efficiency
in using Salesforce. Stay
up-to-date and
keep learning

@salesforcecorporatetrainer

You might also like