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
Pradeep Musthi 9Pradeep Musthi 9 

Update Amount Custom field whenever Related opportunity is Deleted

Here is my Code 
trigger OppAmount on Opportunity (after insert,after update,after delete,after undelete) {
if(Trigger.isInsert || Trigger.isUpdate  || trigger.isUndelete)
{
set<Id> OppId=new Set<Id>();
for(opportunity o:Trigger.new)
{
OppId.add(o.accountid);
}
Decimal i=0;
List<Opportunity> ls=[select amount from opportunity where accountid in:OppId];
List<Account> l=[select id from account where id in:OppId];
List<account> l1=new List<Account>();


for(Opportunity o:ls)
{
if(o.Amount !=null)
{
i=i+(o.Amount);
}
}
for(Account a:l)
{
a.Opportunity_Amount__c=i;
l1.add(a);
}
update l1;
}

if(Trigger.isDelete )
{
Set<Id> accid=new Set<Id>();
for(Opportunity o:Trigger.old)
{
accid.add(o.accountid);
}
List<Account> ls=[select id,Opportunity_Amount__c,(select accountid,amount from opportunities) from account where id in:accid];
list<account> ls2=new list<account>();
decimal i7;
for(Account a:ls)
{

for(opportunity o:a.opportunities)
{

i7= a.Opportunity_Amount__c - (o.Amount);
a.Opportunity_Amount__c=i7;
}

ls2.add(a);
}
update ls2;
}
}

Its Working for insert and Update,but when i delete a particular Opportunity the amount field on trigger is not updating the subtracted value instead it is updating the deleted opportunity amount value
cvuyyurucvuyyuru
Hi Pradeep,

Check this trigger. I didn't test this, but it will work.
trigger OppAmount on Opportunity (after insert,after update,after delete,after undelete) {
	
	set<Id> accountIds = new set<Id>();
	if(Trigger.isInsert || Trigger.isUpdate  || trigger.isUndelete){
		for(Opportunity opp: trigger.new){
			accountIds.add(opp.AccountId);
		}
	}
	
	if(Trigger.isUpdate  || trigger.isDelete){
		for(Opportunity opp: trigger.old){
			accountIds.add(opp.AccountId);
		}
	}
	
	if(!accIds.isEmpty()){
		
		List<Account> lstAccs = new list<Account>();
		for(AggregateResult ar: [Select sum(amount) total, accountId aId from Opportunity where AccountId in: accountIds]){
			lstAccs.add(new Account(id= string.valueOf(ar.get('aId')), Opportunity_Amount__c = decimal.valueOf(ar.get('total'))));
		}
		
		if(!lstAccs.isEmpty())
			update lstAccs;
	}
	
	
}

Let me know if you face any issues.