Skip to content
  • Surfmyindia |
  • Lifedreamguide |
  • w3webmart |
  • Overstockphoto |
  • News24globalworld |
  • News24classictimes |
  • Incriediableindia |
  • TechW3web |
  • W3Force ..
w3web.net
Sign Up to Get Free Code Access β†’ |
  • Home
  • Tutorial
    • Lightning Component
    • Salesforce LWC
    • Salesforce Integration
    • Visualforce
    • Trigger
    • JQuery
  • Get Free Courses
  • Integration
  • Aura Comp
  • Salesforce LWC
  • Visualforce
  • Trigger
  • JQuery
  • React Js
  • More
    • About Us
    • Contact Us
    • Sitemap
    • Course Pricing
    • Blog
    • Gallery
    • Most Popular Articles
    • Download E-Book
    • YouTube Channel


Apex Trigger Whenever Opportunity is: Inserted/Updated/Deleted/Undeleted We need to: Calculate total Amount of all Opportunities Where StageName = ‘Closed Won’ And update it on Account

February 12, 2026 by Vijay Kumar
98 views

Apex Trigger Whenever Opportunity is: Inserted/Updated/Deleted/Undeleted We need to: Calculate total Amount of all Opportunities Where StageName = ‘Closed Won’ And update it on Account

 

Step 1 Create Field on Account

Create Currency field:

πŸ‘‰ Download Free Ebook β†’

πŸ‘‰ Get Complementary β†’

right side banner -- www.w3webmart.com
Field Label API Name
Total Revenue Total_Revenue__c

Data Type β†’ Currency

 

Logic (Same Clean Pattern)

  • Collect AccountIds
  • Run ONE Aggregate SOQL using SUM(Amount)
  • Store result in Map
  • Update Accounts

 

Step 2 Opportunity Trigger (After Update): OpportunityRevenueSumTrigger.apxt

  1. TRIGGER OpportunityRevenueSumTrigger ON Opportunity
  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(Opportunity opp : TRIGGER.new){
  9.             IF(opp.AccountId != NULL){
  10.                 accountIds.add(opp.AccountId);
  11.             }
  12.         }
  13.     }
  14.  
  15.     IF(TRIGGER.isDelete){
  16.         FOR(Opportunity opp : TRIGGER.old){
  17.             IF(opp.AccountId != NULL){
  18.                 accountIds.add(opp.AccountId);
  19.             }
  20.         }
  21.     }
  22.  
  23.     IF(accountIds.isEmpty()){
  24.         RETURN;
  25.     }
  26.  
  27.     // Map TO store total revenue
  28.     Map<Id, Decimal> revenueMap = NEW Map<Id, Decimal>();
  29.  
  30.     // Aggregate Query USING SUM()
  31.     List<AggregateResult> results = [
  32.         SELECT AccountId, SUM(Amount) totalAmount
  33.         FROM Opportunity
  34.         WHERE AccountId IN :accountIds
  35.         AND StageName = 'Closed Won'
  36.         GROUP BY AccountId
  37.     ];
  38.  
  39.     // Store RESULT IN map
  40.     FOR(AggregateResult ar : results){
  41.  
  42.         Id accId = (Id) ar.get('AccountId');
  43.         DECIMAL totalRevenue = (DECIMAL) ar.get('totalAmount');
  44.  
  45.         revenueMap.put(accId, totalRevenue);
  46.     }
  47.  
  48.     List<Account> accountList = NEW List<Account>();
  49.  
  50.     // UPDATE Accounts
  51.     FOR(Id accId : accountIds){
  52.  
  53.         Account acc = NEW Account();
  54.         acc.Id = accId;
  55.  
  56.         acc.Total_Revenue__c = 
  57.             revenueMap.containsKey(accId) ? revenueMap.get(accId) : 0;
  58.  
  59.         accountList.add(acc);
  60.     }
  61.  
  62.     IF(!accountList.isEmpty()){
  63.         UPDATE accountList;
  64.     }
  65. }

 

Why This Is Best Practice?

  • Only ONE SOQL
  • Uses SUM() Aggregate function
  • No SOQL inside loop
  • No DML inside loop
  • Handles Insert, Update, Delete, Undelete
  • Bulk Safe (200 records)
  • Production-ready pattern

 

FAQ (Frequently Asked Questions)

How do I see all opportunities in Salesforce?

In most cases, your list view defaults to Recently Viewed. To toggle to a different list view, click the down arrow next to the list view name and select All Opportunities.

What is the bulkifying trigger in Salesforce?

The benefit of bulkifying your code is that bulkified code can process large numbers of records efficiently and run within governor limits on the Salesforce Platform. These governor limits are in place to ensure that runaway code doesn't monopolize resources on the multitenant platform.

What is the opportunity amount in Salesforce?

For Opportunities with Products, the amount is the sum of the related Products. You cannot directly edit the amount unless the Opportunity has no Products. To change the amount for an Opportunity that contains Products, edit the Sales Price or Quantity of the related Products.

Related Topics | You May Also Like

  • Whenever an Account’s Phone or Email is updated, Update all related Contacts with the same Phone & Email Use @future method (asynchronous processing) in SalesforceWhenever an Account’s Phone or Email is updated, Update all related Contacts with the same Phone & Email Use @future method (asynchronous processing) in Salesforce
  • Write apex trigger on custom Parent Object (Parent__c) to update the related Child Object (Child__c)  Phone whenever Parent__c Phone is Updated | Apex Trigger to update the related Object Phone whenever Parent Phone is updatedWrite apex trigger on custom Parent Object (Parent__c) to update the related Child Object (Child__c) Phone whenever Parent__c Phone is Updated | Apex Trigger to update the related Object Phone whenever Parent Phone is updated
  • 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.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.
  • Apex Trigger Whenever Contact is Inserted/Updated/Deleted/Undeleted We need to count Contacts based on LeadSource and update Account, LeadSource values: Web, Phone Inquiry, Partner Referral, AdvertisementApex Trigger Whenever Contact is Inserted/Updated/Deleted/Undeleted We need to count Contacts based on LeadSource and update Account, LeadSource values: Web, Phone Inquiry, Partner Referral, Advertisement
  • Write a apex trigger on Account, whenever Active is “Yes”, before save the record we will be check the child object (Opportunity) StageName should not be “Closed Lost”, if any of record of child record get “Closed Lost”, it will be through an error.Write a apex trigger on Account, whenever Active is “Yes”, before save the record we will be check the child object (Opportunity) StageName should not be “Closed Lost”, if any of record of child record get “Closed Lost”, it will be through an error.
  • Write Apex Trigger Whenever a Contact is Inserted / Updated / Deleted, We need to Count child Contacts related to each Account Based on MailingCountry Only for these 4 countries (India, USA, England, Japan) Then store the count on Account object.Write Apex Trigger Whenever a Contact is Inserted / Updated / Deleted, We need to Count child Contacts related to each Account Based on MailingCountry Only for these 4 countries (India, USA, England, Japan) Then store the count on Account object.
  • Apex trigger on Account to avoid creation of duplicate record if the account with same phone exists in the system in Salesforce | Write a trigger on Account to Prevent the user to create duplicate Account based on Phone if Phone number is already exist in SalesforceApex trigger on Account to avoid creation of duplicate record if the account with same phone exists in the system in Salesforce | Write a trigger on Account to Prevent the user to create duplicate Account based on Phone if Phone number is already exist in Salesforce
  • Apex Trigger to update Account phone from Contact Phone based on lookup relationship in Salesforce | Update the related Account Phone if Contact Record is Created in SalesforceApex Trigger to update Account phone from Contact Phone based on lookup relationship in Salesforce | Update the related Account Phone if Contact Record is Created in Salesforce

πŸ‘‰ 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



Vijay Kumar

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

Categories Trigger, Tutorial Tags Apex trigger calculate total amount of all opportunities in salesforce example, How to get max(amount of Opportunity for Account in Salesforce), trigger on opportunity to update account field, Trigger to count no of opportunity line item and display in account custom field, Trigger to find sum of all related opportunities amount of an account, write a trigger on contact to sum amount on contact and update account with total amount, Write a trigger to find the max amount of Opportunity and update it in Account, Write a trigger which updates location of opportunity based on ownerid if user location is updated
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.
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

Archives β†’

Categories β†’

  • Agentforce (4)
  • Blog (4)
  • More (7)
  • Tutorial (326)
    • Formula Field (1)
    • JQuery (13)
    • Lightning Component (60)
    • React Js (15)
    • Salesforce Integration (41)
    • Salesforce LWC (115)
    • Trigger (57)
    • Validation Rule (9)
    • Visualforce (16)
  • Uncategorized (4)

Global Visitors β†’

Popular Posts β†’

  • Salesforce REST API Integration Using Postman – Complete Tutorial | Understanding How to Call Salesforce Web Service | Salesforce REST API: A Step-by-Step Guide | Tech W3Web 3.33 views per day
  • add page header or footer into a visualforce -- w3web.net How to make header and footer fixed and repeat on Visualforce page rendered as PDF in Salesforce | How to add header and footer in Visualforce page rendered as PDF in Salesforce 3 views per day
  • trigger to create account Automatically whenever contact is is created -- w3web.net Apex Trigger on Contact to Create Account Automatically and map to related account Id to Contact Whenever New Contact is Created in Salesforce | trigger to create account automatically whenever contact is created in salesforce 2.50 views per day
  • create lightning datatable row actions in lwc -- w3web.net Creating a Lightning Datatable with Row Actions and Display a Modal Popup on Click View Icon Button in Salesforce Lightning Web Component – LWC | how to create lightning datatable row actions in lwc 2.33 views per day
  • create form fields horizontally in lwc -- w3web.net How to align lightning-input form elements horizontally uses of slds-form-element_horizontal css and lightning-card tag in Lightning Web Component – LWC | How to create horizontal input label using slds-form-element/slds-form-element_horizontal... 2.33 views per day
  • Do not allow delete Account, if any of related Contact associated with Account in Salesforce | Prevent the deletion of Account which have related contact through apex trigger in Salesforce 2.33 views per day
  • display different types of toast message in lwc -- w3web.net How to display different types of custom toast message as Error, Success, Info and warning toast notifications on click button, uses of ShowToastEvent property in Salesforce Lightning Web Component — LWC | display custom toast notification in... 2 views per day
  • change stateful button value in lwc -- w3web.net How to change the state of button value as ‘follow/unfollow’ or ‘like/dislike’ through onclick handler method uses of ‘lightning-button-stateful’ tag elements in Salesforce LWC (Lightning Web Component) | How to c... 2 views per day

Get Free Courses β†’

right side banner -- www.surfmyindia.com
right side banner -- overstockphoto.blogspot.com

Join Our Newsletter β†’

Loading
right side banner -- www.lifedreamguide.com

Recent Posts β†’

  • Create a hand-on example as pass input value from parent to child component through PubSub Model LWC in Salesforce
  • How to pass input value from parent to child component through LMS method in Salesforce | Hand-on example as pass input value from parent to child component through Lightning Message Service (LMS) in Salesforce
  • 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
right side banner -- www.w3webmart.com


header banner -- www.overstockphoto.blogspot.com
  • Follow Me β†’
➑ : Facebook
➑ : Twitter
➑ : Linkedin
➑ : Instagram
➑ : Reddit
➑ : Forcetalks
➑ : Pinterest
➑ : Github
➑ : Medium
➑ : Tumblr
➑ : Telegram
 

🧩 Get Free Courses

πŸ‘‰ Get Complementary β†’

right side banner -- www.w3webmart.com
header banner -- www.overstockphoto.blogspot.com

Recent Posts β†’

  • Create a hand-on example as pass input value from parent to child component through PubSub Model LWC in Salesforce
  • How to pass input value from parent to child component through LMS method in Salesforce | Hand-on example as pass input value from parent to child component through Lightning Message Service (LMS) in Salesforce
  • 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
  • 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.
  • Apex Trigger Whenever Contact is Inserted/Updated/Deleted/Undeleted We need to count Contacts based on LeadSource and update Account, LeadSource values: Web, Phone Inquiry, Partner Referral, Advertisement
  • Write Apex Trigger Whenever a Contact is Inserted / Updated / Deleted, We need to Count child Contacts related to each Account Based on MailingCountry Only for these 4 countries (India, USA, England, Japan) Then store the count on Account object.
header banner -- www.lifedreamguide.com

Popular Posts β†’

  • How to pass input value from parent to child component through LMS method in Salesforce | Hand-on example as pass input value from parent to child component through Lightning Message Service (LMS) in Salesforce 7 views
  • Create a hand-on example as pass input value from parent to child component through PubSub Model LWC in Salesforce 6 views
  • create lightning-card container with custom tab in lwc -- w3web.net How to create lightning-card container with custom tab functionality uses a button in the actions slot where we are opening a lightning popup inside a custom form, displaying plain text in the footer slot in Salesforce LWC | How to apply lightning-card to create stylized container around a grouping of information to display different section like Header, Body, Footer and button actions with open a popup inside form in Salesforce LWC (Lightning Web Component) 3 views
  • How to Navigate to External Web Page in LWC – Lightning Web Component | How to use Navigation Service (NavigationMixin.Navigate) to Navigate to External Web Page in LWC 3 views
  • Surfmyindia |
  • Lifedreamguide |
  • w3webmart |
  • Overstockphoto |
  • News24classictimes |
  • TechW3web |
  • Refund Policy |
  • Delivery Policy |
  • Privacy Policy |
  • Term & Conditions
© 2026 w3web.net • Built with GeneratePress

Chat Now