Write a trigger to count number of contacts associated with an account with it's test class.
Whenever new contact is created for an Account update the field Number of contacts(a custom field of type Integer/Number)with the number of contacts. It should also update the count when contact is deleted /removed from Account. The respective count would be increased/Decreased accordingly.
....Trigger.... trigger CountContacts on Contact (after insert, after update, after delete) { list<contact> conList = new list<contact>(); list<account> accList = new list<account>(); set<ID> accIDs = new set<ID>(); if(trigger.isInsert || trigger.isUpdate) { for(contact con : trigger.new) { if(String.isNotBlank(con.accountId)) { accIds.add(con.accountId); } } } if(trigger.isDelete) { for(contact con : trigger.old) { accIDs.add(con.AccountId); } } if(accIDs.size()>0) { conList = [select name, id, accountId from contact where accountId IN:accIDs]; accList = [select name, id , number_of_contacts__c from account where ID IN:accIDs]; } for(account acc : accList) { acc.Number_of_contacts__c = conList.size(); } update accList; }....Test Class...@isTest(SeeAllData = false) public class ContactCountTriggerTest { static testMethod void Testmethod1(){ Account Acc = new Account(); Acc.Name = 'Account 1'; insert Acc; Contact con1 = new Contact(); Con1.lastName = 'con1'; con1.AccountId = Acc.id; Contact con2 = new Contact(); Con2.lastName = 'con2'; con2.AccountId = Acc.id; Contact con3 = new Contact(); Con3.lastName = 'con3'; con3.AccountId = Acc.id; Test.startTest(); insert con1; insert con2; Insert con3; delete con1; Test.StopTest(); } }
Comments
Post a Comment