You need to sign in to do that
Don't have an account?
Paul H 5
UPDATE THE PARENT ACCOUNT FIELD WITH THE OPPORTUNITY NAME THAT HAS HIGHEST AMOUNT
trigger OpportunityTrigger on Opportunity (after insert, after update, after delete, after undelete) {
set<Id> accIds = new set<Id>();
if(trigger.isAfter && trigger.isInsert){
for(Opportunity opp : trigger.new){
if(opp.AccountId != null){
accIds.add(opp.AccountId);
}
}
}
if(trigger.isUpdate && trigger.isUpdate){
for(Opportunity opp : trigger.new){
if(opp.AccountId != Trigger.oldMap.get(opp.Id).AccountId){
accIds.add(opp.AccountId);
accIds.add(Trigger.oldMap.get(opp.Id).AccountId);
}
}
}
if(trigger.isAfter && trigger.isDelete){
for(Opportunity opp : trigger.old){
if(opp.AccountId != null){
accIds.add(opp.AccountId);
}
}
}
List<AggregateResult> aggrList = [Select Name, AccountId, MAX(Amount) maxAmt from Opportunity
where Amount!=null and AccountId IN: accIds
group by Name, AccountId ORDER BY MAX(Amount) desc limit 1];
List<Account> accList = new List<Account>();
for(AggregateResult aggr: aggrList){
Id accId = (Id) aggr.get('AccountId');
String oppName = (String) aggr.get('Name');
Decimal maxOppAmount = (Decimal) aggr.get('maxAmt');
Account acc = new Account(Id= accId,HighestOppAmount__c=oppName);
accList.add(acc);
}
if(accList.size() > 0){
update accList;
}
}
Delete and insert is working fine but I am not getting why my update is not working please check this code
set<Id> accIds = new set<Id>();
if(trigger.isAfter && trigger.isInsert){
for(Opportunity opp : trigger.new){
if(opp.AccountId != null){
accIds.add(opp.AccountId);
}
}
}
if(trigger.isUpdate && trigger.isUpdate){
for(Opportunity opp : trigger.new){
if(opp.AccountId != Trigger.oldMap.get(opp.Id).AccountId){
accIds.add(opp.AccountId);
accIds.add(Trigger.oldMap.get(opp.Id).AccountId);
}
}
}
if(trigger.isAfter && trigger.isDelete){
for(Opportunity opp : trigger.old){
if(opp.AccountId != null){
accIds.add(opp.AccountId);
}
}
}
List<AggregateResult> aggrList = [Select Name, AccountId, MAX(Amount) maxAmt from Opportunity
where Amount!=null and AccountId IN: accIds
group by Name, AccountId ORDER BY MAX(Amount) desc limit 1];
List<Account> accList = new List<Account>();
for(AggregateResult aggr: aggrList){
Id accId = (Id) aggr.get('AccountId');
String oppName = (String) aggr.get('Name');
Decimal maxOppAmount = (Decimal) aggr.get('maxAmt');
Account acc = new Account(Id= accId,HighestOppAmount__c=oppName);
accList.add(acc);
}
if(accList.size() > 0){
update accList;
}
}
Delete and insert is working fine but I am not getting why my update is not working please check this code
Please find below the updated code :
Trigger :
Handler Class :
Hope it is helpful.
Thanks.