Skip to main content
So i'm about 50% into my Learning Salesforce Development with Apex: Write, Run and Deploy Apex Code with Ease (English Edition) book and I'm stuck on the below code. I provide a text version under the image. The below code has no problems. When I create a new task nothing happens though and if I create a task with a Contact it has an issue that says: TaskTrigger: execution of AfterInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.TaskTrigger: line 14, column 1

Question on complex APEX code that shows how to run after insert and after update triggers?Text version of the code from Learning Salesforce Development with Apex: Write, Run and Deploy Apex Code with Ease (English Edition):

trigger TaskTrigger on Task (after insert, after update) {

    switch on Trigger.operationType {

        when AFTER_INSERT {

        Set<Id> contactIds = new Set<Id>();

    For(Task t: Trigger.new) {

    If(t.WhoId != null && String.valueOf(t.WhoId).startsWith('003')) {

    contactIds.add(t.WhoId);

    }

    }

    Map<Id, Contact> contactMap = new Map<Id, Contact> ([SELECT Id, No_Of_Open_Tasks__c FROM Contact WHERE Id in: contactIds]);

    For(Task t :Trigger.new) {

    If(contactMap.containsKey(t.WhoId)) {

    contactMap.get(t.WhoId).No_of_Open_Tasks__c += 1;

    }

    }

    Update contactMap.values();

    }

        when AFTER_UPDATE {            

        Set<ID> contactIds = new Set<Id>();

    For(Task t : Trigger.new) {

    If(t.IsClosed && !Trigger.oldMap.get(t.Id).IsClosed && t.WhoId != null && String.valueOf(t.WhoId).startsWith('003')) {

    contactIds.add(t.WhoId);

    }

    }

    Map<Id, Contact> contactMap = new Map<Id, Contact>([SELECT Id, No_Of_Open_Tasks__c FROM Contact WHERE Id in :contactIds]);

    For(Contact con : contactMap.values()) {

    Con.No_of_open_tasks__c = 0;

    }

    For(AggregateResult ar : [SELECT WhoId, Count(Id) total FROM Task WHERE IsClosed = false AND WhoId in :contactIds GROUP BY WhoID]) {

    String who = String.Valueof(ar.get('WhoId'));

    Decimal total = (Decimal)(ar.get('total'));

    contactMap.get(who).No_of_Open_Tasks__c = total;

    }

    update contactMap.values();

        }

        }

}
4 answers
  1. Dec 26, 2020, 4:53 PM
    nervermind it works:

    nervermind it works:does anyone have an APEX book that they recommend I hate reading a book and the author goes insane with power 100 pages in

    does anyone have an APEX book that they recommend I hate reading a book and the author goes insane with power 100 pages in
0/9000