30 Salesforce Apex Trigger Examples – Part 2

Welcome to the world of Salesforce Apex Triggers! As a Salesforce developer, you must be well aware of the significance of automation and custom logic in optimizing your org’s performance. Apex Triggers are your go-to solution for achieving this goal. In this blog series, we’ll cover the next 10 real-world Salesforce Apex Trigger examples, catering to both beginners and experienced developers.

Note –

Now as we have record-triggered flows in Salesforce, flows become so powerful and because of that we can solve a lot more examples that you are going to see in this article with flows as well, so take these examples for practicing and build the preferred solution.
for example, if a business logic can be implemented with the declarative tools in this case Flow, Salesforce recommends going with a declarative approach over coding/ programming.

 

Salesforce Apex Trigger Examples 👇

Apex Trigger Example 1 –

Your Company XYZ Consulting wants to limit the number of contacts that can be associated with an account to two. In this case, if a user tries to insert or update a Contact record that is associated with an account that already has two or more contacts, this trigger will prevent the operation and display an error message to the user. This will help the company ensure that their account management process remains efficient and avoids unnecessary duplication of contact records.

This  trigger fires on the Contact object before insertion and update events. It counts the number of Contacts associated with an Account and throws an error message if there are already two Contacts related to the same Account.

The trigger first creates a Set of Account Ids from the Contact records being inserted or updated. Then, it queries the Contact object to count the number of Contacts for each Account and stores the count in a Map. If any Contact being inserted or updated is related to an Account with two or more Contacts, the trigger adds an error message to the Contact record to prevent the record from being inserted or updated.

In summary, this trigger enforces a business rule that allows a maximum of two Contacts per Account.

Code –

Explanation –


Apex Trigger Example 2 –

Your company ABC Corp. wants to keep track of the most recent case created for each account so that the customer support team can easily identify which accounts need attention or follow-up. This could also help in analyzing customer satisfaction and identifying trends or recurring issues for a particular account.

Pre Work  :  Create a custom Text field on Account Object named Latest_Case_Inserted__c .

This Apex trigger fires after the insertion of Case records. The trigger checks if the trigger context is after insertion and if any Case records were inserted. If so, it calls the updateLatestCaseNumber method of a class named trgHandler and passes the list of newly inserted Case records as input.

The updateLatestCaseNumber method of the trgHandler class takes the list of Case records as input and updates a custom field Latest_Case_Inserted__c on the parent Account object if the Case is related to an Account. The method first creates a set of unique Account Ids based on the AccountId field of the Case records in the input list. It then queries the database for a map of Account objects based on the Account Ids in the set.

The method then iterates through each Case record in the input list and checks if its AccountId is in the accMap created earlier. If so, it retrieves the corresponding Account object from the accMap and checks if the Latest_Case_Inserted__c field of the Account object is different from the caseNumber field of the Case object. If it is, the Latest_Case_Inserted__c field of the Account object is updated with the caseNumber field of the Case object. Any updated Account objects are added to a map named mapToUpdate.

Finally, if there are any Account objects in the mapToUpdate, the update method is called on their values to update the database.

Code –

 

 

Handler Class :

Explanation –

Learn Complete Salesforce Flows from Basic to Advance

Apex Trigger Example 3-

Your company wants to ensure that they do not create duplicate contacts in their Salesforce CRM system.

The trigger first checks if it is being executed before the insert or update operation on the Contact object. If the trigger is being executed before the insert operation, it will add the email and phone numbers of the new contacts to the emailMap and phoneMap, respectively.

If the trigger is being executed before the update operation, it will compare the old and new email and phone values. If there is a change in either value, the new email or phone number is added to the emailMap or phoneMap.

After the emailMap and phoneMap are populated, the trigger queries the Contact object for any existing contacts that have the same email or phone number. If duplicates are found, the trigger will build an error message that indicates the type of duplicate (email, phone, or both).

Code –

Explanation –

Apex Trigger Example 4 –

Your company wants to notify all contacts associated with an account when the account type is updated.

This code is designed to send an email notification to contacts associated with an account whenever the account type is updated.

The trgHandler class contains a single static method,  trgMethod , that takes in two parameters: a list of updated accounts and a map of old account records. The method first checks which account in the list have had their account type updated by comparing them with the old records. It then creates a set of updated account IDs and uses it to query for associated contacts. For each contact with a non-null email address, the method composes an email message and adds it to a list. Finally, it sends the list of email messages using the Messaging.sendEmail method.

The emailTrg trigger is set to fire after an update to an account and calls the handler class method for each updated account in the trigger context.

Code –

Trigger 

Handler

Explanation –

Apex Trigger Example 5 –

Your Company ABC Corp. wants to keep track of the highest and lowest salaries paid by each of its tech firms to gain insights into how salaries are distributed across different parts of the organization and take appropriate actions to ensure that employee salaries are fair and equitable.

Pre Work :  You need to create 2 Custom Objects . Object – 1 : Tech_Firm__c Fields : Max_Salary__c (Currency) , Min_Salary__c (Currency)

Object – 2 : Employee__c Fields : Salary__c (Currency) , Tech_Firm__c (Lookup)

The trgHandler class has a static method trgMethod that performs various tasks, including creating a set of parentIds to group Employee__c records by their Tech_Firm__c field. The method loops through new Employee__c records in the list and checks if the oldMap is not null. If oldMap is not null, it retrieves the old Employee__c record using the new Employee__c record’s Id. It then checks if the Tech_Firm__c field of the old and new records is different. If it is different, it adds both the old and new Tech_Firm__c Id to the parentIds set. If it is not different, it adds only the new Tech_Firm__c Id to the parentIds set.

Next, the method executes a SOQL query on the Employee__c object to retrieve the maximum and minimum salary for each Tech_Firm__c Id in the parentIds set. It stores the results in an AggregateResult list. The method then loops through the AggregateResult list and creates a map of Tech_Firm__c records to update. It retrieves the Tech_Firm__c Id, maximum salary, and minimum salary from each AggregateResult record and sets them on a new Tech_Firm__c record. It then adds the Tech_Firm__c record to the mapToUpdate map, with the Tech_Firm__c Id as the key.

Afterward, the method loops through the parentIds set and adds a new Tech_Firm__c record to the mapToUpdate map for each Tech_Firm__c Id. It sets the maximum and minimum salary to 0 for each new Tech_Firm__c record. Finally, the method updates the Tech_Firm__c records in the mapToUpdate map.

The trigger, named updateSalary, is defined on the Employee__c object and executed after insert, update, delete, and undelete events. If the trigger is an after update event, the trgHandler.trgMethod method is called with the new Employee__c records and the oldMap. If the trigger is an after delete event, the trgHandler.trgMethod method is called with the old Employee__c records and a null oldMap. If the trigger is an after insert event or an after undelete event, the trgHandler.trgMethod method is called with the new Employee__c records and a null oldMap.

Code –

Trigger 

 

Handler Class 

Explanation –

Apex Trigger Example 6 –

A Sales Organization wants to track the largest Opportunity associated with each of its Accounts. This information could be used to prioritize sales efforts, allocate resources, or identify opportunities for cross-selling or upselling.

Pre Work : Create a Custom field on Account Object named maxOpp__c (Text) to store Opportunity Name.

The trigger handler class, ‘trgHandler’, contains a single static method, ‘trgMethod’, which takes two arguments: a list of Opportunity records (oppList) and a map of the previous versions of these records (oldMap). The method begins by creating an empty set of Account IDs (parentIds), which will be used to store the IDs of all the Accounts that need to be updated.

The method then checks if the oppList parameter is not empty, and if so, iterates over each Opportunity in the list. If the oldMap parameter is not null, the method compares the AccountId field of the old and new versions of the Opportunity. If the IDs are different, the method adds both Account IDs to the parentIds set. If the IDs are the same, the method adds only the new Account ID to the set. If the oldMap parameter is null, the method simply adds the new Account ID to the set.

Once all the relevant parent Account IDs have been collected, the method queries the Account object to retrieve the current values of the ‘maxOpp__c’ and related Opportunities fields for each parent Account. For each Account, the method then checks if there are any related Opportunities with non-null values for the ‘Amount’ field. If so, the method updates the ‘maxOpp__c’ field on the Account with the name of the Opportunity that has the highest value for ‘Amount’. If there are no related Opportunities with non-null ‘Amount’ values, the method sets the ‘maxOpp__c’ field to an empty string. Finally, the method adds each modified Account to a list (listToUpdate) and updates them in a single DML statement.

The trigger itself, ‘maxTrg’, fires after insert, update, delete, and undelete events on the Opportunity object. The trigger handler method is called with different arguments depending on the type of event that triggered the trigger. For update events, the trigger passes the new and old versions of the Opportunity records to the handler. For delete events, the trigger passes only the old versions of the records. For insert and undelete events, the trigger passes only the new versions of the records.

Code –

Trigger

 

Handler Class

Explanation –

Apex Trigger Example 7-

Your Company ABC Consulting wants to ensure that only one primary contact is associated with an account to avoid confusion and duplication of effort. By enforcing this rule, businesses can ensure that all communications and interactions with the account are streamlined and consistent.

Pre Work : Create a Checkbox Field named Primary_Contact__c  on Contact.

This code defines a handler class called trgHandler that contains a single static method called trgMethod. This method takes two parameters: a list of Contact  records and a map of old  Contact records. The method checks whether any Contact records have changed their parent AccountId, and if so, adds those parent  AccountId values to a set called parentIds. It then queries for all Contact records with those parent AccountId values that have a Primary_Contact__c field set to true, and creates a map called conMap that associates each parent AccountId with the number of Contact records with a Primary_Contact__c field set to true. Finally, the method iterates over the original list of Contact records and adds an error message to any records where the Primary_Contact__c field is true and the associated parent AccountId in the conMap map has a count greater than zero.

The second part of the code is a trigger called limitTrg that is fired before an insert or update on Contact records. The trigger passes the new Contact records and the old Contact records to the trgMethod method of the trgHandler class depending on the trigger event.

Code –

Trigger

 

Handler Class

Explanation –

Apex Trigger Example 8 –

Let’s say a sales rep is working on an account and marks the “Close_all_Opps__c” field as true. Without this trigger, they would have to manually go through each open opportunity for that account and close them as won, which can be time-consuming and prone to errors. With this trigger in place, the opportunities will be automatically closed as won if they meet the criteria specified in the code.

Pre Work : Create a custom field on Account Object named Client_Contact__c – Lookup(Contact).

The code defines a class named “trgHandler” with a static method named “trgMethod”. This method accepts a List of Account objects as input parameters. The purpose of this method is to create a new Contact object for each Account in the input List, and associate it with the corresponding Account’s Id. If the Contact object is successfully created, the Client_Contact__c field of the corresponding Account is updated with the Id of the newly created Contact object.

The trigger “createClientConTrg” is defined on the Account object and it is executed after an insert operation on an Account object. It checks if the trigger context is “after insert” and if there are any new Account objects in the trigger context. If there are any new Account objects, it calls the trgHandler.trgMethod() method and passes the List of new Account objects to it.

Code –

Trigger

 

Handler Class

Explanation –

Apex Trigger Example 9 –

Your organization wants to maintain a list of client contacts for each of their customer accounts. The organization might have multiple contacts associated with each customer account, and they want to keep track of the primary contact for each customer account.

Code –

 

Handler Class

Explanation –

Apex Trigger Example 10 –

Your organization sells products to their customers through opportunities. Each opportunity can have multiple products (Opportunity Line Items) associated with it. The organization wants to keep track of the total number of products sold to each account and display it on the Account record for reporting purposes.

Pre Work : Create a custom field on the Account object named Number_of_Products__c (Number) to count the total number of products related to all Opportunities associated with the Account.

This code includes a trigger and a handler class that updates the Number_of_Products__c field of an Account record based on the number of OpportunityLineItem records related to the Account.

The trigger, named grandChildTrg, is fired on the after-insert and after-delete events of the OpportunityLineItem object. When an OpportunityLineItem is inserted, the trigger calls the trgMethod method of the trgHandler class with the new OpportunityLineItem records as a parameter. When an OpportunityLineItem is deleted, the trigger calls the same method as the old OpportunityLineItem records as a parameter.

The trgMethod method of the trgHandler class first creates a set of Opportunity Ids by iterating through the OpportunityLineItem records in the parameter list. It then retrieves a list of Opportunities that correspond to these Ids. For each Opportunity, the method creates an entry in a map, oliMap, with the Opportunity’s AccountId as the key and 0 as the initial value.

Next, the method performs an AggregateResult query on the OpportunityLineItem object to count the number of OpportunityLineItem records related to each AccountId in the oliMap. The query results are then used to update the corresponding values in the oliMap.

Finally, the method creates a new list of Account records with the updated Number_of_Products__c field, based on the values in the oliMap. This list is then updated using the DML statement “update”.

Code –

Trigger

 

Handler Class

Explanation –

 

Salesforce Apex Trigger Examples Part 2

Share Now

Shubham is the Founder of Salesforce Geek. He is also a Salesforce Certified Consultant.

Similar Posts

One thought on “30 Salesforce Apex Trigger Examples – Part 2

Leave a Reply

Your email address will not be published. Required fields are marked *