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
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
Berer berseBerer berse
As the world continues to grapple with the COVID-19 crisis of 2020, it is becoming increasingly clear that the ability to continue learning must be maintained in order to minimize the long-term implications for students, teachers, and education systems. Fortunately, there is a wide range of online resources available to support the continuity of learning during this unprecedented time. In this t mo co refill20 (https://handstations.co.uk/product/5l-hand-sanitiser-70-alcohol-gel-dispenser-refill-20-litre-bulk-deal-4x-5-litre-refills/) blog, we will explore how educators and students can leverage these online resources to ensure that learning continues despite the challenges posed by the pandemic.
Shri RajShri Raj
trigger CoronaCountyTrigger on Patient__c (after insert, after update, after delete) {
    if (Trigger.isInsert || Trigger.isUpdate || Trigger.isDelete) {
        CoronaCountyHelper.calculateAvgDays(Trigger.new, Trigger.old);
    }
}
 
public with sharing class CoronaCountyHelper {
    public static void calculateAvgDays(List<Patient__c> newPatients, List<Patient__c> oldPatients) {
        Set<Id> countyIds = new Set<Id>();
        List<County__c> countyList = new List<County__c>();
        
        // Get the unique county IDs
        for (Patient__c patient : newPatients) {
            countyIds.add(patient.County__c);
        }
        for (Patient__c patient : oldPatients) {
            countyIds.add(patient.County__c);
        }

        // Calculate the average days for each county
        for (Id countyId : countyIds) {
            List<Patient__c> patients = [SELECT Id, State__c, CreatedDate, Cured_Date__c, Fatal_Date__c                                          FROM Patient__c                                          WHERE County__c = :countyId];
            Integer daysToRecover = 0, daysUntilFatal = 0;
            Integer curedCount = 0, fatalCount = 0;

            for (Patient__c patient : patients) {
                if (patient.State__c == 'Cured') {
                    daysToRecover += (patient.Cured_Date__c - patient.CreatedDate).days();
                    curedCount++;
                }
                if (patient.State__c == 'Fatal') {
                    daysUntilFatal += (patient.Fatal_Date__c - patient.CreatedDate).days();
                    fatalCount++;
                }
            }
            
            County__c county = new County__c(
                Id = countyId,
                AVG_Days_Until_Fatal__c = fatalCount > 0 ? daysUntilFatal / fatalCount : null,
                AVG_Days_To_Recover__c = curedCount > 0 ? daysToRecover / curedCount : null
            );
            countyList.add(county);
        }

        // Update the counties
        if (countyList.size() > 0) {
            update countyList;
        }
    }
}

In this updated code, the trigger is now correctly invoking the calculateAvgDays method on the CoronaCountyHelper class. The helper class calculates the average days to recover and average days until fatality for each county and stores the values in the AVG_Days_Until_Fatal__c and AVG_Days_To_Recover__c fields on the County__c object, respectively.
Note: You need to make sure that the Cured_Date__c and Fatal_Date__c fields exist on the Patient__c object and that the County__c object has fields AVG_Days_Until_Fatal__c