1

Scenario: When a new Case is created with a specific recordtype I want to change the Case Contact to a default Account Contact instead of the Contact initially set when case is created. (These cases are created automatically when they come in via email).

Since workflow rules do not allow me to do field update on Case Contact, I am attempting to do this via a combination of WFR and a Trigger.

The WFR checks to see if all the base criteria are met:

Contact.Callhome_Contact__c <> null &&
RecordType.Name = "Callhome Alert"

Contact.Callhome_Contact__c is a related lookup field on Contact that is used to specify what Account Contact should be used as the default contact for these types of cases.

If the above evaluates to TRUE field update sets:

Update_Callhome_Contact__c = TRUE

The Trigger is then called before update and attempts to set the Contact to the Callhome_Contact:

trigger CaseCallhomeContact on Case (before update) {

    for (Case c :Trigger.new) {

        if (c.Update_Callhome_Contact__c) {
            c.ContactId = Trigger.oldMap.get(c.id).Contact.Callhome_Contact__c;
            c.Update_Callhome_Contact__c = FALSE;                
        }
    }   
}

I have tried various ways of setting c.ContactId = c.Contact.Callhome_Contact__c or c.Contact.Callhome_Contact__r.Id, but so far everything I have tried has resulted in a value of NULL.

Could some kind soul please point out the likely obvious error in my approach?

1 Answer 1

1

In triggers, you can't access relationships from the Trigger variables - you'll have to query for the fields you want. I think I understand the relationships you have between objects, so this code should work, but I might have a few details off. However, the general approach should handle what you need.

trigger CaseCallhomeContact on Case (before update) {
   //create an empty list to hold the contact IDs
   List<Id> contactIds = new List<Id>();
    for (Case c :Trigger.new) {    
        if (c.Update_Callhome_Contact__c) {
            //add the contact ids to the list
            contactIds.add(c.ContactId);         
        }
    }

    //Query for the contacts and add them to a map
    Map<Id, Contact> callhomeContactsMap = new Map<Id, Contact>([SELECT Id, Callhome_Contact__c FROM Contact WHERE Id IN :contactIds]);

    //Loop back through the cases and use our new map to get the Callhome_Contact__c value
    for(Case c :Trigger.new) {
       c.ContactId = callhomeContactsMap.get(c.ContactId).Callhome_Contact__c;
       c.Update_Callhome_Contact__c = FALSE;       
    }
}
2
  • Made a couple syntax edits to your answer. This works perfectly! Thank You!
    – AaronC
    Oct 30, 2014 at 17:21
  • Awesome, glad to hear it worked!
    – jongpie
    Oct 30, 2014 at 17:58

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .