function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
honey sonihoney soni 

Help in Write a basic Trigger on Opportunity ?

i want write a trigger on Opportunity,When a Opportunity is 'close won' after that trigger update the related account's Custome Field Sum_of_CloseWon__C ,with the amount of closed won Opportunity 'Amount' Field ..
Thanks in advance. ;)
 
Best Answer chosen by honey soni
BALAJI CHBALAJI CH
Hi Honey Soni,

Please find below Trigger on Opportunity for your requirement.
 
trigger TaskOpportunity on Opportunity (after update, after insert) {
    
    Set<Id> AccntIds = new Set<Id>();
    Map<String,Decimal> AccountAmounts = new Map<String,Decimal>();
    for(opportunity op : Trigger.New)
    {
        if(op.StageName == 'Closed Won' && op.Amount != Null)
        {
            AccntIds.add(op.AccountId);
            AccountAmounts.put(op.AccountId, op.Amount);
        }
    }
    
    List<Account> UpdatedAccounts = new List<Account>();
    
    for(Account ac : [select id, Sum_of_CloseWon__C from Account where Id IN : AccntIds])
    {
        ac.Sum_of_CloseWon__C = AccountAmounts.get(ac.Id);
        UpdatedAccounts.add(ac);
    }
    update UpdatedAccounts;
}
Let us know if that helps you.

Best Regards,
BALAJI
 

All Answers

BALAJI CHBALAJI CH
Hi Honey Soni,

Please find below Trigger on Opportunity for your requirement.
 
trigger TaskOpportunity on Opportunity (after update, after insert) {
    
    Set<Id> AccntIds = new Set<Id>();
    Map<String,Decimal> AccountAmounts = new Map<String,Decimal>();
    for(opportunity op : Trigger.New)
    {
        if(op.StageName == 'Closed Won' && op.Amount != Null)
        {
            AccntIds.add(op.AccountId);
            AccountAmounts.put(op.AccountId, op.Amount);
        }
    }
    
    List<Account> UpdatedAccounts = new List<Account>();
    
    for(Account ac : [select id, Sum_of_CloseWon__C from Account where Id IN : AccntIds])
    {
        ac.Sum_of_CloseWon__C = AccountAmounts.get(ac.Id);
        UpdatedAccounts.add(ac);
    }
    update UpdatedAccounts;
}
Let us know if that helps you.

Best Regards,
BALAJI
 
This was selected as the best answer
sfdcLionsfdcLion
Hi Honey,

You can try this.
trigger OpportunityTrigger on Opportunity(after insert, after update){
//Declare a collection to hold AccountIds
set<Id> setAccIds = new set<Id>();
List<Account> lstAccToUpdate = new List<Account>();

//Loop through the Opportunities to fetch Parent Account Ids. 
// CHeck if event is Insert
if(Trigger.isInsert){
 for(Opportunity opp : Trigger.new){
     setAccIds.add(opp.AccountId);
 }
}

//For update event, check for if there is a change in Parent Account - if possible in your case or if //there is update in Amount field on Opportunity or if stages are changed 
// write the similar if condition

//Once setAccIds is prepared by looping on Opportunities, write Parent to Child SOQL
for(Account accRec :[SELECT Id,Sum_of_Closed_Won__c, (SELECT Id,Amount,Stage from Opportunities WHERE       Stage ='Closed WON')]{
   if(accRec.Opportunities.size()>0){
     Decimal sum = 0;
     for(Opportunity opp : accRec.Opportunities){ // perform the sum of all the closed won //opportunities  per account
         sum = sum + opp.Amount;
     }
     // assign the variable sum to Account's custom field.
     accRec.Sum_Of_Closed_Won__c = sum;
     // Add the affected account records to a collection
     lstAccToUpdate.add(accRec);
   }
}

//update the list of Account, perform appropriate Exception Handling
update lstAccToUpdate;
}



-SK
Ajay K DubediAjay K Dubedi
Hi Honey,
     Hope this trigger will solve your problem:
 
trigger toUpdateAmount on Opportunity (before update) {
List<Account> accList = new List<Account>();
set<Id> accIdset = new set<Id>(); 
List<Opportunity> oppList = new List<Opportunity>();
for(Opportunity oppo: trigger.new){
if(oppo.StageName == 'Closed Won'){
accIdset.add(oppo.AccountId);
oppList.add(oppo);
}
}
accList = [SELECT Id,Sum_of_CloseWon__C FROM Account where Id in :accIdset];
for(Opportunity op : oppList){
for(Account ac : accList){
    if(ac.Sum_of_CloseWon__C ==null){
        ac.Sum_of_CloseWon__C =0;}
if(op.AccountId ==ac.Id){
ac.Sum_of_CloseWon__C = ac.Sum_of_CloseWon__C + op.Amount;
}
}
}



Regards,
Ajay
sfdcLionsfdcLion
@Balaji - As per my understanding. Your piece of code will work only if there is one Opportunity (Closed Won) exists under an Account. If there are multiple Closed Won Opportunities under parent Account than this code logic will give inappropriate results. Let me know or help with understanding.

@Ajay - Wanted to share my understanding that this use case might not be valid or go well with before update trigger event. 
ManojjenaManojjena
Hi Honey ,

try with below code
 
Trigger RollUpFromChildToParent on Opportunity ( after update,after delete,after undelete) {
	Set<Id> accIdSet=new Set<Id>();
	List<Account> accListToUpdate=new List<Account>();
	if(Trigger.isUpdate ){
		for(Opportunity opp : Trigger.new){
			if(opp.AcccountId != null && Trigger.oldMap.get(opp.id).Status != opp.Status && opp.Status=='closed own'){
			    accIdSet.add(opp.AcccountId);  
			}
		}
	}If(Trigger.isDelete){
		for(Opportunity opp : Trigger.old){
			if(opp.AcccountId != null && opp.Status=='closed own'){
			accIdSet.add(opp.AcccountId);   
			}

		}
	}If(Trigger.isundelete){
		for(Opportunity opp : Trigger.new){
			if(opp.AcccountId != null && opp.Status=='closed own'){
				accIdSet.add(opp.AcccountId);
			}
		}
	}
	for(AggregateResult res : [SELECT AcccountId,sum(Amount)can FROM Opportunity WHERE AcccountId IN :accIdSet AND Status='Closed Own' GROUP BY AcccountId]) {
		accListToUpdate.add(new Account(Id=(Id)res.get('AcccountId'),Sum_of_CloseWon__c=(Double)res.get('can')));
	}
	try{
		update accListToUpdate;
	}catch(DmlException de){
		System.debug(de);
	}
}
Let me know if it helps !!
Thanks
Manoj