2

I have the apex trigger below that is meant to check the WhatId on a new Task if the WhatId belongs to a case. The trigger then populates fields on the related Case for ActivityDate and Task Type. This works as intended so long as the trigger encounters a task related to only a Case. If the Task is related to a Lead, I receive a null pointer exception on line 6, which is where I check for the sObjectType of the WhatId. Any assistance with this would be much appreciated!

trigger taskToCaseService on Task (after insert) {

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

    for(Task t: Trigger.new) {
        If(t.whatId.getsObjectType() == Case.sObjectType){
            caseIdSet.add(t.whatId);
        }       
    }

    if(!caseIdSet.isEmpty()) {
        Map<Id, Case> caseMap = new Map<Id, Case>([Select Id, Task_Date_Time__c, Scheduled_Task_Type__c from Case where Id =: caseIdSet]);
        for(Task t: Trigger.new) {
            If(t.whatId.getsObjectType() == Case.sObjectType){
                Case c = caseMap.get(t.whatId);
                if(c != null) {
                    c.Scheduled_Task_Type__c = t.Type;
                    c.Task_Date_Time__c = t.ActivityDate;
                }
            }
        }

        if(!caseMap.isEmpty())
            update caseMap.values();
    }    
}
1

You can easily handle this you just need to put a null check. It is used to make sure that whatId is not null.

for(Task t: Trigger.new) {
        If(t.whatId != null && t.whatId.getsObjectType() == Case.sObjectType){
            caseIdSet.add(t.whatId);
        }       
    }
  • 1
    Tushar, Nailed it! That totally slipped my mind. Thank you! – Marc Swan Sep 20 '17 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.