+ Start a Discussion
John Neilan 2John Neilan 2 

Pull Contacts Into A Case

Hello,

I am trying to see if I can pull Contacts into a Case when it is created.  When a Case is created under a certain record type, I want to be able to pull in any Contacts marked as Primary that are associated with the Account that the Case is also associated to.  Does anyone know if this is possible and have any examples of how to do it?  I need this because I am also setting up a WFR Email alert to send to all the primary contacts for an Account.  Thanks,
@Karanraj@Karanraj
Yes, you can write apex trigger on Case object to update the Primary contact of account automatically for the case record. Make sure that there won't be more than one primary contact is enabled for account record. I assume that you already have custom field in contact object to identify whether it is primary contact or not
trigger updatePrimaryContact on Case (before insert,before update) {

List<Id> accountIdList = new List<Id>();
for(case caseRecord : trigger.New){
if(caseRecord.AccountId != Null){
accountIdList.add(caseRecord.AccountId);
}
}

Map<Id,Id> mapAcctContact = new Map<Id,Id>();
for(Account acc: [Select Id,(Select Id from Contacts where isPrimary__c = 'True' Limit 1) from Account where Id IN:accountIdList]){
 if(acc.Contacts.size() > 0)
  mapAcctContact.put(acc.Id,acc.Contacts[0].Id);
}
 
for(Case CaseRecord : Trigger.New){  
  caseRecord.ContactId = mapAcctContact.get(caseRecord.AccountId);
}

}

 
John Neilan 2John Neilan 2
Thanks.  My issue is that the email is being sent from the Account via a WFR, but I need to be able to send it to multiple Contacts associated with the Account that are marked as Primary via a custom checkbox on the Contact.  Is this possible with a trigger?