+ Start a Discussion
Salesforce seekarSalesforce 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);
        }

    }
Sainath VenkatSainath Venkat

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
 
Dhanya NDhanya N
Hello,

You can create Rollup Summary field on Account and select MAX aggregate function on Amount field. No need of code.

Thanks,
Dhanya
Salesforce seekarSalesforce seekar
hello Dhanya and sainath , 

i want to see how to remove  nested for scenario works basically .  so i want it in  trigger only , can you please help me
Dhanya NDhanya N
Hi,

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
set<Id> setAccountId = new set<Id>();
List<Account> accountListToUpdate = new List<Account>();

for(Opportunity opp : trigger.new) {
	setAccountId.add(opp.AccountId);
}
List<AggregateResult> aggregateResultList = [Select Id, Name, AccountId, Max(Amount) amt from Opportunity Where AccountId IN: setAccountId];

if(aggregateResultList != null && aggregateResultList.size() > 0) { 
	for(AggregateResult aggr: aggregateResultList){ 
		Account acc = new Account(Id = (id) aggr.get('AccountId'));
		acc.Amount__c = (decimal) aggr.get('amt');
		accountListToUpdate.add(acc);
	}
}
if(!accountListToUpdate.isEmpty()) 
	update accountListToUpdate;

Thanks,
Dhanya