0

I have a custom Object MyObject__c which has one field Contact__c lookup on Contact object and trigger on it. I want trigger to update ContactName field of MyObject__c when ever Contact object is deleted.I could see that LastModifiedDate of MyObject__c is getting updated on Contact record delete but trigger is not fired.

trigger ContactNameUpdate on MyObject__c (before insert,before update) {
    List<MyObject__c> stObjects = Trigger.new;
    system.debug('Inside trigger '+JSON.serialize(stObjects));
    for(MyObject__c st : stObjects){
            st.ContactName__c = st.Contact__r.Name;
        }
}

What I am missing in above code? Please leave comment if problem is not clear.

Thanks

1 Answer 1

1

First of, no need to cast the trigger.new

Second, the Relationship Name will ALWAYS be null in the trigger context.

3rd, Simply use a formula field to get the name no need for a trigger

But in case you do not wish to use a formula field (not sure why you would not but...) here is code to do what you want

trigger ContactNameUpdate on MyObject__c (before insert,before update) {
  Map<ID,String> recToName = New Map<ID,Name>();

  for(MyObject__c mo : trigger.new){
      if(mo.Contact__c != null)
        recToName.put(mo.Contact__c,null);
  }

  for(Contact c : [Select Name From Contact Where ID IN :recToName.keySet()]){
      recToName.put(c.id,c.Name);
  }

    for(MyObject__c st : trigger.new){
            //st.ContactName__c = st.Contact__r.Name; //Contact__r.Name will always be null unless you query for it
         st.ContactName__c = st.Contact__c == null ? null : recToName.get(st.Contact__c);
        }
}
8
  • st.ContactName__c = st.Contact__c == null ? null : recToName.get(st.Contact__c); will always assign null.
    – San
    Commented Jun 22, 2015 at 18:26
  • @San - How do you figure? If Contact__c is null it assigns null, if it is not, it get the Map value for the key
    – Eric
    Commented Jun 22, 2015 at 18:51
  • But you put null in map recToName.put(mo.Contact__c,null); even if it is not null.
    – San
    Commented Jun 22, 2015 at 18:53
  • @San - Follow the code - Look at the second for loop. The first loop just populates the IDs to use in the query
    – Eric
    Commented Jun 22, 2015 at 19:02
  • @San - Why are you even bothering with the code anyway. Just use a formula field. Why would you not be able to do that?
    – Eric
    Commented Jun 22, 2015 at 19:03

You must log in to answer this question.

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