Scenario: A new Account Lookup field is created and on the Case object.
then, once an Account is selected and saved –
The Primary’ Contact name and email-address associated with the Account
should be auto-populated to case.
How can I get a handle on the contact.id to get info from the Contact Map?
public static void updatePrimaryContactInfo(List<Case> newCases, Map<Id, Case> oldCases ) {
try {
List<Case> casesToUpdate = new List<Case>();
Map<Id, Contact> primContactsMap = new Map<Id, contact>();
Set<Id> ctAccountIdsList = new Set<Id>();
casesToUpdate = newCases;
for ( Case c : casesToUpdate ) {
if ( c.AccountId != null) {
ctAccountIdsList.add( c.AccountId);
}
}
if ( !casesToUpdate.isEmpty() && !ctAccountIdsList.isEmpty() ) {
primContactsMap = new Map<Id, Contact>([SELECT Id,Name,AccountId FROM Contact WHERE AccountId IN :ctAccountIdsList AND contact.primary__c = true]);
}
for ( Case c : casesToUpdate) {
listCt = new list <contact>([ SELECT Id,Name,AccountId FROM Contact WHERE contact.AccountId = c.AccountId]) ; // Err: Unexpected token!
if ( primContactsMap.get(listCt.id) != null ) {
c.Contact_Name__c = primContactsMap.get(listCt.id).Name;
c.Contact_Email__c = primContactsMap.get(listCt.id).Email;
} else {
c.Contact_Name__c = null;
}
}
} catch (Exception ex) {
CreateExceptionLog.insertErrorLog(ex, null, null, null, 'Apex', 'Case', 'CaseTrigger', 'CaseTriggerHelper.PrimaryContact()', 'High');
}
}
Best Answer
You need to iterate over the Contacts you query into
primContactsMap
to build another map ofAccountId
to Primary Contact.This won't work:
for several reasons (it's not bulkified, needs a
:
for variable binding, andList
doesn't have anId
). Instead, you need thatMap<Id, Contact>
where the Map keys are the Account Ids.You could do something like this to generate it:
Then you can do
primContactsMap.get(c.AccountId)
to find the primary contact for a specific Case. You shouldn't check that value fornull
, though - if you need to know if you have a primary contact, doprimContactsMap.containsKey(c.AccountId)
.