[SalesForce] count number of records

I have create trigger and its handler class to count child records for particular parent.

Trigger countRecord on contact (after insert) {
if(Trigger.isInsert){
contr.afterinsert(Trigger.new);
}

}

Best Answer

I think the issue is with your handler class: if there are no Subject Visits left when you delete then you need to query the parent Site record not the child records. One approach I've seen is to query the parent records with a subquery of the child records and setting the parent record to the size of the child list.

this is handler class
public class SubjectTriggerHandler {
    public static void perform(Set<Id> Ids){
      List<CTMS__Clinical_Site__c> CSToUpdate = new List<CTMS__Clinical_Site__c>([SELECT Id, Subject_Visit_Count__c, (SELECT Id FROM CTMS__Subject_Visits__r) FROM CTMS__Clinical_Site__c WHERE Id IN :Ids]);


        for (CTMS__Clinical_Site__c site : CSToUpdate){
            site.Subject_Visit_Count__c = site.CTMS__Subject_Visits__r.size();
        }
           update CSToUpdate;  
    }
 }
Related Topic