You need to sign in to do that
Don't have an account?
Salesforce seekar
trigger using maps to remove nested for loops
Hello Folks ,
My scenario: under account say i have 4 opportunities each having Opportunity.Amount__c field , i want to show show the Max value of Amount out of 4 opportunities under that account on Account.Amount__c field.
I want it only using maps ,
no nested for loops please like below.
list < Account > AccList = new list < Account > ([Select id, Name, (Select id, Amount from opportunities) from Account ]);
Map<Accid,Opportunity> Opptoupdate = new Map<Accid,Opportunity>();
for( Account account : AccList) {
for(Opportunity opportunity : account.opportunities) {
if(opportunity.Amount == null || Opptoupdate.get(opportunity.AccountId).Amount > opportunity.Amount) {
Opptoupdate.put(opportunity.AccountId, opportunity);
}
}
My scenario: under account say i have 4 opportunities each having Opportunity.Amount__c field , i want to show show the Max value of Amount out of 4 opportunities under that account on Account.Amount__c field.
I want it only using maps ,
no nested for loops please like below.
list < Account > AccList = new list < Account > ([Select id, Name, (Select id, Amount from opportunities) from Account ]);
Map<Accid,Opportunity> Opptoupdate = new Map<Accid,Opportunity>();
for( Account account : AccList) {
for(Opportunity opportunity : account.opportunities) {
if(opportunity.Amount == null || Opptoupdate.get(opportunity.AccountId).Amount > opportunity.Amount) {
Opptoupdate.put(opportunity.AccountId, opportunity);
}
}
Your class should do the following
* Loop through the trigger opps and create a set of account IDs.
* Use a SQL relational query to get a list of Accounts with related opps based on the account ID set you just created:
Account[] accts = [select Id, Loan_Name__c, (select Name, Amount from Opportunities order by Amount DESC limit 1) from Account where Id in :acctIdSet];
* Loop through the account list and set your custom field to the opp name using this syntax:
for(Account acct : accts) {
acct.Loan_Name__c = acct.Opportunities[0].Name;
}
Hope it helps
You can create Rollup Summary field on Account and select MAX aggregate function on Amount field. No need of code.
Thanks,
Dhanya
i want to see how to remove nested for scenario works basically . so i want it in trigger only , can you please help me
You can use Aggregate Result function. Trigger should be on Opportunity.
Here is a reference for Aggregate result : https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_agg_fns.htm
Thanks,
Dhanya