Apex Trigger Whenever Opportunity is Inserted/Updated/Deleted/Undeleted We need to count how many Opportunities have: StageName = ‘Closed Won’ And update that count on Account.

79 views

Apex Trigger Whenever Opportunity is Inserted/Updated/Deleted/Undeleted We need to count how many Opportunities have: StageName = ‘Closed Won’ And update that count on Account.

 

Step 1 Create Fields on Account

Create Number field on Account:

πŸ‘‰ Download Free Ebook β†’

πŸ‘‰ Get Complementary β†’

right side banner -- www.w3webmart.com
Field Label API Name
Closed Won Opportunities Closed_Won_Count__c

Data Type β†’ Number (0 decimal)

 

Logic (Same Clean Pattern)

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

 

Step 2 Account Trigger (After Update): OpportunityClosedWonCountTrigger.apxt

  1.  
  2.    TRIGGER OpportunityClosedWonCountTrigger ON Opportunity
  3. (after INSERT, after UPDATE, after DELETE, after undelete) {
  4.  
  5.     Set<Id> accountIds = NEW Set<Id>();
  6.  
  7.     // Collect AccountIds
  8.     IF(TRIGGER.isInsert || TRIGGER.isUpdate || TRIGGER.isUndelete){
  9.         FOR(Opportunity opp : TRIGGER.new){
  10.             IF(opp.AccountId != NULL){
  11.                 accountIds.add(opp.AccountId);
  12.             }
  13.         }
  14.     }
  15.  
  16.     IF(TRIGGER.isDelete){
  17.         FOR(Opportunity opp : TRIGGER.old){
  18.             IF(opp.AccountId != NULL){
  19.                 accountIds.add(opp.AccountId);
  20.             }
  21.         }
  22.     }
  23.  
  24.     IF(accountIds.isEmpty()){
  25.         RETURN;
  26.     }
  27.  
  28.     // Map TO store Closed Won COUNT
  29.     Map<Id, Integer> closedWonMap = NEW Map<Id, Integer>();
  30.  
  31.     // Aggregate Query
  32.     List<AggregateResult> results = [
  33.         SELECT AccountId, COUNT(Id) totalCount
  34.         FROM Opportunity
  35.         WHERE AccountId IN :accountIds
  36.         AND StageName = 'Closed Won'
  37.         GROUP BY AccountId
  38.     ];
  39.  
  40.     // Store RESULT IN map
  41.     FOR(AggregateResult ar : results){
  42.  
  43.         Id accId = (Id) ar.get('AccountId');
  44.         INTEGER countValue = (INTEGER) ar.get('totalCount');
  45.  
  46.         closedWonMap.put(accId, countValue);
  47.     }
  48.  
  49.     List<Account> accountList = NEW List<Account>();
  50.  
  51.     // UPDATE Accounts
  52.     FOR(Id accId : accountIds){
  53.  
  54.         Account acc = NEW Account();
  55.         acc.Id = accId;
  56.  
  57.         acc.Closed_Won_Count__c = 
  58.             closedWonMap.containsKey(accId) ? closedWonMap.get(accId) : 0;
  59.  
  60.         accountList.add(acc);
  61.     }
  62.  
  63.     IF(!accountList.isEmpty()){
  64.         UPDATE accountList;
  65.     }
  66. }

 

Why This Is Best Practice?

  • Only ONE SOQL
  • Uses AggregateResult
  • No SOQL inside loop
  • No DML inside loop
  • Handles Insert, Update, Delete, Undelete
  • Bulk safe (200 records)
  • Easy to explain in interview

 

FAQ (Frequently Asked Questions)

What happens when an opportunity is closed won?

In Salesforce and other CRMs, β€œClosed Won” is the term used for successfully closing a deal with a prospect. This means that they have agreed to purchase your product or service and are now considered a customer.

How to see more than 2000 records in Salesforce?

Salesforce will simply show the first 2000 in the UI, and to get the rest you can press the Export button on the top-right corner.

Which comes first, lead or opportunity?

You want to qualify leads, thus making them prospects, and then nurture those prospects into promising opportunities. The journey of lead to prospect to opportunity is a pathway to success.

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