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
adi salesforceadi salesforce 

Trigger to update accounts description with its related contacts description by separating with a comma

Raj VakatiRaj Vakati
trigger ContactUpdate on Contact (after insert) {

set<Id> acctIds = new set<Id>();
for(Contact con : trigger.new) {
	acctIds.add(con.AccountId);
}
List<Account> accs = [Select Id ,Description , (Select Id, LastName ,Description from Contacts) from Account where Id in :acctIds] ;

for(Account a :accs){
	List<String> cnons = List<String>() ;
	for(Contact c :a.Contacts){
		cnons.add(c.Description);
	}
	String strCntry = '';
for(String s:cnons) {
strCntry += (strCntry == ''?'':',')+s;

}
idString = idString.substring(0, idString.length()-1);
a.Description = idString ;



	
}

Update accs;

}

 
Bhargavi TunuguntlaBhargavi Tunuguntla
Hi Adi

Try the below code:
 
trigger ContactTrigger on Contact (before insert,before update,after insert,after update) {
    
    if(Trigger.isAfter)
    {
        if(Trigger.isInsert||Trigger.isUpdate)
        {
            
            //Update Account description with related contact description
            Set<Id> accIds=new Set<Id>();
            Map<Id,String> AccDesc=new Map<Id,String>();
            
            for(Contact c:Trigger.new)
            {
               if(c.Description!=trigger.oldMap.get(c.Id).description)
                { 
                accIds.add(c.AccountId);
                if(AccDesc.containsKey(c.AccountId))
                {
                    String descp=AccDesc.get(c.AccountId);
                    descp=descp+','+c.Description;
                    AccDesc.put(c.AccountId,descp);
                }
                else
                {
                   AccDesc.put(c.AccountId,c.Description); 
                }
                }
            }
            if(accIds.size()>0){
            List<account> accList=new List<Account>([select id,Description from Account where id in: accIds]);
            for(Account acc:accList)
            {
                if(AccDesc.containsKey(acc.Id))
                {
                    if(acc.Description!=null)
                    acc.description=acc.Description+','+AccDesc.get(acc.Id);
                    else
                    acc.description=AccDesc.get(acc.Id);    
                }
            }
            update accList;
			}
            
        }
      
        
    }
}

Hope this will be helpful.This worked for me perfectly.

Thanks​​​​​​​