I'm trying to count the number of contacts at an account with a specific status.
So if any contacts at the account have a status of 'A', that should set the Account Stage (on the account) to 'A Working'. Whereas if any have a status of 'B', it should set the Account Stage to 'B Working'. Otherwise, the Account Stage should be set to 'Not Working'.
This works when I've used two separate aggregate queries, but I'd prefer to only use one query. To do this, I've tried to use a map containing the contact statuses but it isn't working because I'm not sure how to relate the map to the account?
global without sharing class contactTriggerHandler {
Public static void Method(List < contact > newcontact) {
String Owner;
String AssignedTo;
String Type;
Set < Id > accountIds = new Set < Id > ();
for (contact con: newcontact) {
accountIds.add(con.accountid);
Type = con.Account_Type__c;
}
List<contact> contacts = [
SELECT
Id,status__c,accountid
FROM contact
WHERE accountid in :accountIds
];
Map<String, List<contact>> mapstatusToAccountList = new Map<String, List<contact>>();
Map <Id, Account> lstAccountsToUpdate = new Map <Id, Account> ();
for(contact contactstocount : contacts){
if(mapstatusToAccountList.keyset().contains(contactstocount.status__c)){
mapstatusToAccountList.get(contactstocount.status__c).add(contactstocount);
} else {
mapstatusToAccountList.put(contactstocount.status__c,
New List<contact>{contactstocount});
}
}
next part:
for (Account acc: [
SELECT Id, Name,Account_Stage__c
from Account
where Id IN: accountIds FOR UPDATE
]) {
Account accObj;
if (lstAccountsToUpdate.containsKey(acc.Id)) {
accObj = lstAccountsToUpdate.get(acc.Id);
} else {
accObj = new Account(Id = acc.Id);
lstAccountsToUpdate.put(acc.Id, accObj);
}
if (mapstatusToAccountList.get('Assigned A').size() > 1 ) {
accObj.Account_Stage__c = 'A Working';
}
if (mapstatusToAccountList.get('Assigned B').size() > 1 ) {
accObj.Account_Stage__c = 'B Working';
}
else{
accObj.Account_Stage__c = 'Not Working';
}
}
if (lstAccountsToUpdate.size() >0) {
UPDATE lstAccountsToUpdate.values();
}
}
}
global
access modifier. If you actually need it, you will know you need it and why.