0

I have been trying to develop a trigger which isnt working, The requirement is that I have an email field that should auto-populate once contact has been assigned to the case "Seconday_Contact__c" is the contact name and "Secondary_Contact_Email__c" is the email field.

the trigger is


    trigger populateContactemail on Case (before insert , before update){
Set<ID> setConIds = new Set<ID>();
for(Case  obj : trigger.new){
    if(obj.Secondary_Contact__c != null)
        setConIds.add(obj.Secondary_Contact__c);
}
MAP<ID , Case> mapCon = new MAP<ID , Case>([Select Secondary_Contact_Email__c from Case where id in: setConIds]);
for(Case obj : trigger.new)
{
    if(obj.Secondary_Contact__c != null)
    {
        Case  c = mapCon.get(obj.Secondary_Contact__c);
        obj.eSecondary_Contact_Email__c = c.email;
    }
}}
  • 1
    Why not use a formula field? – David Reed Sep 12 at 17:30
  • Is Secondary_Contact__c a lookup to Case? Looks like it should be a lookup to Contact. If that's the case, you're querying the wrong object. – Sebastian Kessel Sep 12 at 17:35
  • Secondary_Contact__c is lookup field to contact!. – Sammy Sep 12 at 17:37
  • Your queries are wrong, then. Answer forthcoming. – Sebastian Kessel Sep 12 at 17:52
2

If Secondary_Contact__c is a lookup to Contact, you're then querying the wrong object.

This is how I'd do it.

trigger populateContactEmail on Case (before insert , before update){
    Set<Id> setConIds = new Set<Id>();

    for (Case  obj : trigger.new) {
        if (obj.Secondary_Contact__c != null) {
            setConIds.add(obj.Secondary_Contact__c);
        }
    }

    Map<Id, Contact> mapCon = new Map<Id, Contact>([Select Id, Email from Contact where id in: setConIds]);

    for (Case obj : trigger.new) {
        if (obj.Secondary_Contact__c != null) {
            //Protecting against bad Ids
            if (mapCon.containsKey(obj.Secondary_Contact__c) {
                Contact c = mapCon.get(obj.Secondary_Contact__c);
                obj.eSecondary_Contact_Email__c = c.Email;
            }
        }
    }
}

PS: I took the liberty of doing some code formatting and casing to adjust to best practices and normal conventions.

PPS: As David Reed mentioned on his comment, this could very well be better made as a formula field. I am correcting your trigger for education purposes, but you should probably prefer a formula here, or even a Process Builder, instead of a trigger.

  • 1
    Thanks that works like a charm – Sammy Sep 12 at 17:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.