Last active
June 22, 2020 02:51
-
-
Save salesforce-casts/7ff19d98c7014bec489cbf890499919c to your computer and use it in GitHub Desktop.
1. Query Accounts put it in a map<Id, Rating> 2. Query and get related records, map of account to related records 3. If Rating is Hot then update all the child records with Hot so on and so forth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class exploreTestOne { | |
String localAccountId; | |
Set<Id> accountIds = new Set<Id>(); | |
List<Contact> finalContacts = new List<Contact>(); | |
public Map<Id, List<Id>> accountContacts{set; get;} | |
Map<Id, String> accountRatingMap = new Map<Id, String>(); | |
public exploreTestOne(){ | |
accountContacts = new Map<Id, List<Id>>(); | |
} | |
public void foobar(){ | |
List<Account> accounts = [SELECT Id, Rating FROM Account]; | |
Map<Id, Account> accountsMap = new Map<Id, Account>([SELECT Id, Rating FROM Account]); | |
Map<Id, Contact> contactsMap = new Map<Id, Contact>([SELECT Id FROM Contact]); | |
for(Account a : accounts){ | |
accountRatingMap.put(a.Id, a.Rating); | |
} | |
AggregateResult[] groupedResults = [SELECT Id, AccountId FROM Contact WHERE AccountId IN: accounts GROUP BY Id, AccountId]; | |
for(AggregateResult ar : groupedResults){ | |
localAccountId = (Id)ar.get('AccountId'); | |
if(accountIds.contains(localAccountId)){ | |
//get values and update the list in the map | |
List<Id> existingList = accountContacts.get(localAccountId); | |
existingList.add((Id)ar.get('Id')); | |
accountContacts.put(localAccountId, existingList); | |
}else{ | |
//add a new entry into the list and add it to the map | |
accountIds.add(localAccountId); | |
List<Id> onlyId = new List<Id>(); | |
onlyId.add((Id)ar.get('Id')); | |
accountContacts.put(localAccountId, onlyId); | |
} | |
} | |
for(Id accountId : accountContacts.keySet()){ | |
List<Id> relatedContacts = accountContacts.get(accountId); | |
Account localAccountRec = accountsMap.get(accountId); | |
if(localAccountRec.Rating == 'Hot'){ | |
for(Id conId : relatedContacts){ | |
Contact localContactRec = contactsMap.get(conId); | |
localContactRec.LastName = 'Hot'; | |
finalContacts.add(localContactRec); | |
} | |
} | |
update finalContacts; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<apex:page controller="exploreTestOne" action="{! foobar }"> | |
{! accountContacts } | |
</apex:page> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment