• divakar u 9
  • NEWBIE
  • 0 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 4
    Questions
  • 3
    Replies
write trigger on contact to update account field based on contact field
parent object: account
   fields : contact country - Picklist values: India, Africa, America
   child object : contact
   field : Contact Area - Picklist values: Karataka, Andhra Pradesh, Kerala, South Africa, Nigeria, Kenya, California, San Fransisco, Texas

   when contact is inserted / updated, based the contact's Contact Area field the parents contact Country should change with respected country. wirte a trigger for insert, Update.
trigger ContactSumTrigger on Contact (After insert, After delete, After undelete) {
    Set<Id> parentIdsSet = new Set<Id>();
    List<Account> accountListToUpdate = new List<Account>();
    IF(Trigger.IsAfter){
        IF(Trigger.IsInsert || Trigger.IsUndelete){
            FOR(Contact c : Trigger.new){
                if(c.AccountId!=null){   
                   parentIdsSet.add(c.AccountId); 
                }
            }
        }
        IF(Trigger.IsDelete){
            FOR(Contact c : Trigger.Old){
                if(c.AccountId!=null){   
                   parentIdsSet.add(c.AccountId); 
                }
            }
        }
    }
    System.debug('#### parentIdsSet = '+parentIdsSet);
    List<Account> accountList = new List<Account>([Select id ,Name, Number_of_Contacts__c, (Select id, Name From Contacts) from Account Where id in:parentIdsSet]);
    FOR(Account acc : accountList){
        List<Contact> contactList = acc.Contacts;
        acc.Number_of_Contacts__c = contactList.size();
        accountListToUpdate.add(acc);
    }
    try{
        update accountListToUpdate;
    }catch(System.Exception e){
        
    }
}
error : Number_of_Contacts__c variable doesnt exist ; line 21 and 24