+ Start a Discussion
Robert Lange 6Robert Lange 6 

Trying to set up trigger and helper class for Corona Virus data

I am trying to write Apex code for the following:

Covid 19 Info

Area-Holds info about all covid19 patients in an area
Patient - A person infected with covid 19.  It has a field called state (mild/critical/cured/fatal)

Area and Patient share a lookup relationship

Find out-
1. Avg days to recover in that area (Cured date - CreatedDate)
2. Avg days of fatality (Fatal data - CreatedDate)

Trigger and helper class are below.  I don't have any errors with the code, but I can't get it working.  Any help would be appreciated.  Thank you.
 
trigger CoronaCountyTrigger on Patient__c (after insert, after update, after delete) {

    if (Trigger.isInsert || Trigger.isAfter || Trigger.isDelete) {
        if (Trigger.isAfter) {
            CoronaCountyHelper.avgFatal();
        }
    }
}
 
public with sharing class CoronaCountyHelper {
    public static void avgFatal() {
        Set<Id> countyIds = new Set<Id>();
        List<County__c> countyList = new List<County__c>();
        List<Patient__c> patientList = Trigger.isInsert || Trigger.isUpdate ? Trigger.new : Trigger.old;
        for (Patient__c pat1 : patientList) {
            countyIds.add(pat1.County__c);
        }

        for (AggregateResult ag : [
                SELECT County__c, AVG(Days_Until_Fatal__c) avg1
                FROM Patient__c
                GROUP BY County__c
        ]) {
            countyList.add(new County__c(
                    Id = (Id) ag.get('County__c'),
                    AVG_Days_Until_Fatal__c = (Integer) ag.get('avg1')));
        }

        if (countyList.size() > 0) {
            update countyList;
        }
    }
}

 
SarvaniSarvani
Hi Robert,

You have to pass the trigger context variables trigger.new or trigger.old to apex class (Handler) from trigger like in the below example. 

https://developer.salesforce.com/forums/?id=9060G0000005VDMQA2

Hope this helps!

Thanks