0

I'm trying to create a trigger that sets a case status to "closed" if there are more than 2 cases created that day associated with the same contact. This is so far what I have written, but I'm getting a null pointer exception on line 33 (if(myRelatedCases.size() > 1)).

trigger CloseCase on Case (before insert) {

    //Creating a List to store all the records in trigger.new
    List<String> ids = new List<String>();

    //Adding all the IDs to List<String> ids
    for(Case myCase : Trigger.new) {
        if(myCase.ContactId != null) {
            ids.add(myCase.ContactId);
        }

    }

    //Query all the cases Created today with a ContactId contained ids list
    List<Case> relatedCases = [SELECT Id, Status FROM Case
                                                      WHERE ContactId in :ids AND CreatedDate = TODAY];

    //Create a map of id to list of cases created today (Originally I was working with the email)
    Map<String,List<Case>> emailToCase = new Map<String, List<Case>>();

    //Looping the relatedCases list and add the records to the emailToCase map
    for(Case theCase : relatedCases) {
        if(!emailToCase.containsKey(theCase.ContactId)) {
            emailToCase.put(theCase.ContactId, new List<Case>() );
        }
        List<Case> entries = emailToCase.get(theCase.ContactId);
        entries.add(theCase);
    }

    //Loop my list of cases in trigger.new and get the amount of cases created today
    for(Case myCase : Trigger.new) {
        List<Case> myRelatedCases = emailToCase.get(myCase.ContactId);
        if(myRelatedCases.size() > 1) {
            myCase.Status = 'Closed';
        }       
    }
}
2

This is going to happen every time you get a Case whose Contact has no other Cases that match the query

SELECT Id, Status FROM Case WHERE ContactId in :ids AND CreatedDate = TODAY

You populate an entry in emailToCase for each Contact whose Id comes up in the Cases that are returned by this query. But, as your code is showing you, there must always be a first Case for any given Contact on some day, and there won't be any results from the query.

As a result, emailToCase.get(someContactId) will return null, which is assigned to myRelatedCases. When you call myRelatedCases.size(), the NullPointerException ensues.

Simple fix? Check if it's null first.

    if(myRelatedCases != null && myRelatedCases.size() > 1) {

Short-circuit evaluation ensures that if myRelatedCases is null, myRelatedCases.size() will never be called, and you're safe from the NullPointerException.

Your code is already bulkified effectively and will use exactly 1 SOQL and 0 DML per trigger invocation.

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.