[SalesForce] How to populate Contact info to Case object when Account Lookup field is selected in Case

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 of AccountId to Primary Contact.

This won't work:

       listCt = new list <contact>([ SELECT Id,Name,AccountId FROM Contact WHERE contact.AccountId = c.AccountId]) ;  // Err: Unexpected token!
    if ( primContactsMap.get(listCt.id) != null ) {

for several reasons (it's not bulkified, needs a : for variable binding, and List doesn't have an Id). Instead, you need that Map<Id, Contact> where the Map keys are the Account Ids.

You could do something like this to generate it:

primContactsMap  = new Map<Id, Contact>();
for (Contact c : [SELECT Id,Name,AccountId FROM Contact WHERE AccountId IN :ctAccountIdsList  AND contact.primary__c = true]) {
    primContactsMap.put(c.AccountId, c);
}

Then you can do primContactsMap.get(c.AccountId) to find the primary contact for a specific Case. You shouldn't check that value for null, though - if you need to know if you have a primary contact, do primContactsMap.containsKey(c.AccountId).