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
sri m 6sri m 6 

Update Account when contact is inserted

Hi,

How to assign all contacts last name in the related account objects description field using trigger?H
Shashikant SharmaShashikant Sharma
Hi,

You just need to write a After Insert Trigger on Contact. In your trigger code loop over newly contacts and update the related accounts. Like below.
 
Trigger Trigger_AccountUpdateOnContactInsert on Contact ( After Insert ) {


  Map<Id, Account> accountToUpdate = new Map<Id, Account>();
 // loop over newly inserted contact
  for( Contact con : Trigger.new ) {

     if( con.AccountId != null )  {
             // create new instance of account to be updated   
            Account acc = new Account( Id = con.AccountId );
            acc.Description = con.LastName;
            
           accountToUpdate.put( acc.Id, acc );
      }
  } 
  
  if( accountToUpdate.size() > 0 ) {
      // update accounts
      update accountToUpdate.values();
  }
     
}


I hope above would help you resolving your issue.

Thanks

Shashikant
 

Ajay K DubediAjay K Dubedi
Hi Sri,
Try below code:

Apex Class:
public with sharing class AccountDescriptionUpdate {
    public static void method(list<Contact> conList)
  {
   list<Id> idsforUpdate=new list<Id>();
      for(Contact con:conList)
      {
       idsforUpdate.add(con.AccountId);
      }
      
      map<Id,Account> mapofAccount=new map<Id,Account>([select id,name,description from Account where id=:idsforUpdate]);
      list<Account> updateList=new list<Account>();
      for(Contact con:conList)
      {
       Account ac=mapofAccount.get(con.AccountId);
       ac.Description=ac.description+' '+con.LastName;
          updateList.add(ac);
      }
      if(updateList.size()>0)
      {
          Update updateList;
      }
  }
}
Trigger:
trigger DescriptionUpdateTrigger on Contact (after insert) {
       list<Contact> updateList=new list<Contact>();
 for(Contact con:Trigger.new)
 {
     if(con.AccountId !=null)
     {
         updateList.add(con);
     }
 }
   if(updateList.size()>0)
   {
       AccountDescriptionUpdate.method(updateList);
   }
}
I hope, this code will help you

Regards,
Ajay