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
julian1.391156003193672E12julian1.391156003193672E12 

Update Contact using trigger when changing Account on Case.

Dear Gurus,

Need your help on the following

[Scenario]
  • Person Account is on the org
  • When changing Account on Case, expected Contact is automatically changed. It was not.
  • I wrote a trigger as follows to enforce changing Contact on Account change.
  • Unfortunately it was not working though there was no error.
[Code]

trigger trgGetContactInfo on Case (before insert, before update, after insert, after update) {

    for(Case cas  : Trigger.New) 
        {    
            //Trigger Action Logic 
            List<Account> accList = [Select id from Account where id =: cas.AccountId]; 
                
            for(Account acc : accList) 
                { 
                    List<Contact> conList = [Select id, name from Contact where id =: acc.id];

                    for(Contact con : conList)
                        {
                            cas.ContactId = con.id;
                        }
                }
      // update cas;
        } 
}

Thanks for your help in advance.
Julian Lee 
vinothvinoth
Hi,
I think you made a mistake in the below line,

List<Contact> conList = [Select id, name from Contact where id =: acc.id acc.contactid];

In where condition you are trying to compare contact id with account id.  you can use
          either
where id =: acc.contactid
           or
where account =: acc.id

Thanks,
Vinoth
julian1.391156003193672E12julian1.391156003193672E12
Finally working with the code below. Thanks a Vinoth.

[Code]
trigger trgGetContactInfo on Case (before update) {

    for(Case cas  : Trigger.New) 
        {    
            //Trigger Action Logic 
            List<Account> accList = [Select id from Account where id =: cas.AccountId]; 
                
            for(Account acc : accList) 
                { 
                    List<Contact> conList = [Select id, name from Contact where AccountId =: acc.id];

                    for(Contact con : conList)
                        {
                            cas.ContactId = con.id;
                        }
                }
        } 
}