function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Dipti DDipti D 

Need help updating a lookup field. - Trigger

Hi, 
Can someone help me with a trigger? I need to Update 'Contact Name' field on Case Object. 'Contact Name' should be the 'Account Name' - as we are using person accounts. Case has lookup relation with both Account & Contact. If someone has a trigger for this, please help. Thanks
I tried to update the Contact Name (lookup field) via workflow rules & process builder, but nothing helped as it is a lookup field. 


User-added image
RohRoh
Hello Dipti ,
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.
The trigger should be on Contact Object rather than case object because you will have multiple cases assigned to a contact and you need to update the name whenever the Account name changes.

trigger CaseAssignNameContact on Contact (After update,After Insert) {

if(Trigger.isAfter){

    //Query for the contacts and add them to a map
    List<Case> caseUpdateList = new List<Contact>([SELECT Id,Contact From Case WHERE ContactId IN :trigger.New]);
    //Loop back through the cases and use our new map to get the Callhome_Contact__c value
    List<case> upsertList = new List<Case>
    for(Case c :caseUpdateList)
    {
        c.Contact = trigger.New[0].Name ;
        upsertList.add(c) ;
        
    }
    upsert upsertList ;
  }
}

PS : IF YOU FIND THIS ANSWER HELPFUL PLEASE DONT FORGET TO LIKE IT AND CHOOSE IT AS THE BEST ANSWER.

Regards,
Roh