Apex Trigger Whenever Case is: Inserted/Updated/Deleted/Undeleted We need to count Cases based on Priority: High, Medium, Low And update counts on Account

83 views

Apex Trigger Whenever Case is: Inserted/Updated/Deleted/Undeleted We need to count Cases based on Priority: High, Medium, Low And update counts on Account

 

Step 1 Create Fields on Account

Create 3 Number fields:

๐Ÿ‘‰ Download Free Ebook โ†’

๐Ÿ‘‰ Get Complementary โ†’

right side banner -- www.w3webmart.com
Field Label API Name
High Priority Cases High_Priority_Cases__c
Medium Priority Cases Medium_Priority_Cases__c
Low Priority Cases Low_Priority_Cases__c

Data Type โ†’ Number (0 decimal)

 

Logic Pattern (Same Clean Structure)

  • Collect AccountIds
  • Run ONE Aggregate SOQL
  • Store result in separate Maps
  • Update Accounts

 

Step 2 Case Trigger (After Update): CasePriorityCountTrigger.apxt

  1. TRIGGER CasePriorityCountTrigger ON CASE
  2. (after INSERT, after UPDATE, after DELETE, after undelete) {
  3.  
  4.     Set<Id> accountIds = NEW Set<Id>();
  5.  
  6.     // Collect AccountIds
  7.     IF(TRIGGER.isInsert || TRIGGER.isUpdate || TRIGGER.isUndelete){
  8.         FOR(CASE cs : TRIGGER.new){
  9.             IF(cs.AccountId != NULL){
  10.                 accountIds.add(cs.AccountId);
  11.             }
  12.         }
  13.     }
  14.  
  15.     IF(TRIGGER.isDelete){
  16.         FOR(CASE cs : TRIGGER.old){
  17.             IF(cs.AccountId != NULL){
  18.                 accountIds.add(cs.AccountId);
  19.             }
  20.         }
  21.     }
  22.  
  23.     IF(accountIds.isEmpty()){
  24.         RETURN;
  25.     }
  26.  
  27.     // Separate maps FOR each priority
  28.     Map<Id, Integer> highMap = NEW Map<Id, Integer>();
  29.     Map<Id, Integer> mediumMap = NEW Map<Id, Integer>();
  30.     Map<Id, Integer> lowMap = NEW Map<Id, Integer>();
  31.  
  32.     // Aggregate Query
  33.     List<AggregateResult> results = [
  34.         SELECT AccountId, Priority, COUNT(Id) totalCount
  35.         FROM CASE
  36.         WHERE AccountId IN :accountIds
  37.         AND Priority IN ('High','Medium','Low')
  38.         GROUP BY AccountId, Priority
  39.     ];
  40.  
  41.     // Store counts IN respective maps
  42.     FOR(AggregateResult ar : results){
  43.  
  44.         Id accId = (Id) ar.get('AccountId');
  45.         String priorityValue = (String) ar.get('Priority');
  46.         INTEGER countValue = (INTEGER) ar.get('totalCount');
  47.  
  48.         IF(priorityValue == 'High'){
  49.             highMap.put(accId, countValue);
  50.         }
  51.         ELSE IF(priorityValue == 'Medium'){
  52.             mediumMap.put(accId, countValue);
  53.         }
  54.         ELSE IF(priorityValue == 'Low'){
  55.             lowMap.put(accId, countValue);
  56.         }
  57.     }
  58.  
  59.     List<Account> accountList = NEW List<Account>();
  60.  
  61.     // UPDATE Accounts
  62.     FOR(Id accId : accountIds){
  63.  
  64.         Account acc = NEW Account();
  65.         acc.Id = accId;
  66.  
  67.         acc.High_Priority_Cases__c =
  68.             highMap.containsKey(accId) ? highMap.get(accId) : 0;
  69.  
  70.         acc.Medium_Priority_Cases__c =
  71.             mediumMap.containsKey(accId) ? mediumMap.get(accId) : 0;
  72.  
  73.         acc.Low_Priority_Cases__c =
  74.             lowMap.containsKey(accId) ? lowMap.get(accId) : 0;
  75.  
  76.         accountList.add(acc);
  77.     }
  78.  
  79.     IF(!accountList.isEmpty()){
  80.         UPDATE accountList;
  81.     }
  82. }

 

Why This Is Best Practice?

  • Single Aggregate SOQL
  • Uses GROUP BY AccountId, Priority
  • No SOQL inside loop
  • No DML inside loop
  • Fully bulkified
  • Easy to explain
  • Production-ready pattern

 

FAQ (Frequently Asked Questions)

What are the major limitations of apex triggers?

Your Apex triggers (combined) must not exceed 200 SOQL queries per batch. If they do, your Clean job for that object fails. In addition, if your triggers call future methods, they're subject to a limit of 10 future calls per batch.

What are common Apex trigger mistakes?

Summary. Salesforce Triggers are essential for automating business logic, but common mistakes like not bulkifying code, writing logic directly in triggers, missing recursion control, and hardcoding values can lead to performance issues and deployment failures.

What are the two types of triggers in Salesforce?

Before Triggers: These triggers are used to update or validate triggering record values before they're saved to the database. After Triggers: These are used to access fields values that are already set by the system like recordId, lastModifiedDate field for performing after save actions like sending mail.

Related Topics | You May Also Like

๐Ÿ‘‰ Get Complementary โ†’

right side banner -- www.w3webmart.com
 
  
๐Ÿ‘‰ Get Free Course โ†’

๐Ÿ“Œ Salesforce Administrators

๐Ÿ“Œ Salesforce Lightning Flow Builder

๐Ÿ“Œ Salesforce Record Trigger Flow Builder

๐Ÿ‘‰ Get Free Course โ†’

๐Ÿ“Œ Aura Lightning Framework

๐Ÿ“Œ Lightning Web Component (LWC)

๐Ÿ“Œ Rest APIs Integration



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net