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:
| 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
TRIGGER OpportunityClosedWonCountTrigger ON Opportunity
(after INSERT, after UPDATE, after DELETE, after undelete) {
Set<Id> accountIds = NEW Set<Id>();
// Collect AccountIdsIF(TRIGGER.isInsert || TRIGGER.isUpdate || TRIGGER.isUndelete){
FOR(Opportunity opp : TRIGGER.new){
IF(opp.AccountId != NULL){
accountIds.add(opp.AccountId);
}}}IF(TRIGGER.isDelete){
FOR(Opportunity opp : TRIGGER.old){
IF(opp.AccountId != NULL){
accountIds.add(opp.AccountId);
}}}IF(accountIds.isEmpty()){
RETURN;}// Map TO store Closed Won COUNT
Map<Id, Integer> closedWonMap = NEW Map<Id, Integer>();
// Aggregate QueryList<AggregateResult> results = [
SELECT AccountId, COUNT(Id) totalCount
FROM OpportunityWHERE AccountId IN :accountIds
AND StageName = 'Closed Won'
GROUP BY AccountId
];// Store RESULT IN map
FOR(AggregateResult ar : results){
Id accId = (Id) ar.get('AccountId');
INTEGER countValue = (INTEGER) ar.get('totalCount');
closedWonMap.put(accId, countValue);
}List<Account> accountList = NEW List<Account>();
// UPDATE Accounts
FOR(Id accId : accountIds){
Account acc = NEW Account();
acc.Id = accId;
acc.Closed_Won_Count__c =
closedWonMap.containsKey(accId) ? closedWonMap.get(accId) : 0;
accountList.add(acc);
}IF(!accountList.isEmpty()){
UPDATE accountList;}}
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
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 Free Course β
π Salesforce Administrators π Salesforce Lightning Flow Builder π Salesforce Record Trigger Flow Builder |
π Get Free Course β |



