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
PeteyBirdPeteyBird 

First Trigger Help

Hello all,

 

My first foray into writing a trigger (which I think is what I need to do based on the details below).  I've found a ton of info online which I think has gotten me close, but I'm at a roadblock.


What I'm trying to do is increment a field Number_of_Injuries on a custom object Course by 1 every time a Case is saved where Case.Incident_Type (a custom field on case) is "Injury."

 

The code below returns a result: Error:Apex trigger updateInjuryCount caused an unexpected exception, contact your administrator: updateInjuryCount: execution of AfterUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.updateInjuryCount:

 

I would truly appreciate any guidance experts may have on this.

 

trigger updateInjuryCount on Case (after update, after insert)
{
    
    Integer i = 0;
    
    Set<ID> courseIDs = new Set<ID>(); //variable to store the course id that is used in the case lookup field
    
    Map<ID, integer> id2Injury = new Map<ID, integer>();
    
    for (Case o : Trigger.new) //define case as variable o, when the trigger is first fired
    {
        if ((Trigger.isInsert && o.Incident_Type__c == 'Injury') ||
            Trigger.old[i].Incident_Type__c != o.Incident_Type__c)
        {
            courseIDs.add(o.Course__c); //get the course id from the lookup field on case object
            
            id2Injury.put(o.Course__c, 1); //creates array with course id and integer to increment
        }     
        i++;    
    }
    
    List<Course__c> courses = [select id, Number_of_Injuries__c from Course__c where id in :courseIDs]; //finds the relevant course record
    
    for (Course__c c : courses)
    {
        c.Number_of_Injuries__c++;
    }
    
    update courses;
}

Best Answer chosen by Admin (Salesforce Developers) 
Jake GmerekJake Gmerek

So that means that that line is not the cause of your issue.  I would insert a few more debug statements to find out where your error is.  Something should be coming up null.  Once we figure out where the error is occuring then we can fix it.

All Answers

Jake GmerekJake Gmerek
Ok you have a few things going on here, but most likely your issue is caused by this line:

List<Course__c> courses = [select id, Number_of_Injuries__c from Course__c where id in :courseIDs]; //finds the relevant course record

not returning any courses. Then when you go to use the courses list it blows up on you. You should probably add another check like if(courses != null and courses.size() > 0) before your final for statement so that courses are only updated if they exist. But that probably raises greater issues about the quality of your data.

Other things I noticed:

1. id2injury is not used anywhere it is just created and filled. If there is no use for it you should remove it as it just confuses things.

2. This trigger as written will update the course record whenever Incident_Type__c is updated regardless of what it is updated to. You probably have a logic error in your if statement.

3. Your trigger is not bulkified. Read here for more info:

http://wiki.developerforce.com/page/Best_Practice:_Bulkify_Your_Code

Let me know if you have more questions
PeteyBirdPeteyBird

Hi Jake,


Thanks for the guidance.  I'm still getting the error after adding the if statement.  I added a system.debug before the if and commented it and everything after out and am getting this message in the debug log:


|USER_DEBUG|[28]|DEBUG|The value is: (Course__c:{Id=a01i00000018TOiAAM})

 

This id is close to referencing the id for the course I'm trying to update, but it has three characters appended at the end "AAM".

 

Any idea why it would be doing that?  I'm assuming that's why it's getting through the "if" statement you suggested, since it isn't null or of zero length.  Planning to bulkify after I get this working, just trying to take it one step at a time...

Jake GmerekJake Gmerek
So that means that it is finding a course. The extra letters are OK b/c there are two versions of every ID one 15 character and one 18 character. You are just seeing the 18 character version. Although this can cause some issues, it will not cause the one that you are seeing in your first post.

What are you actually putting in your debug statement, the output is not what I would expect?
PeteyBirdPeteyBird

Here's the debug code:

System.debug('The value is: ' + courses);

 

Here's the entire relevant entry in the debug log:

 

13:40:14.134 (134227000)|USER_DEBUG|[28]|DEBUG|The value is: (Course__c:{Id=a01i00000018TOiAAM})
I continue to appreciate any advice you may have.

Jake GmerekJake Gmerek

So that means that that line is not the cause of your issue.  I would insert a few more debug statements to find out where your error is.  Something should be coming up null.  Once we figure out where the error is occuring then we can fix it.

This was selected as the best answer
PeteyBirdPeteyBird

It appears to be working now, not sure what I did!

 

Now I need to bulkify and learn how to increase the code coverage.

 

Any ideas on why this would have stopped showing up in the debug log? I didn't realize it was working because I kept expecting to see the process in the log (hence all of the System.debug lines) but tripped into it when I went to a Course record and found that the Number of Injuries field had been updated.

trigger updateInjuryCount on Case (after update, after insert) 
{
    System.debug('hello');
    
    Integer i = 0;
    
    Set<ID> courseIDs = new Set<ID>(); //variable to store the course id that is used in the case lookup field
    
    for (Case o : Trigger.new) //define case as variable o, when the trigger is first fired
    {
        if ((Trigger.isInsert && o.Incident_Type__c == 'Injury') ||
            Trigger.old[i].Incident_Type__c != o.Incident_Type__c)
        {
            courseIDs.add(o.Course__c); //get the course id from the lookup field on case object

           // id2Injury.put(o.Course__c, 1); //creates array with course id and integer to incremen
   
        }     
        i++;    
    }
    
    List<Course__c> courses = [select id, Number_of_Injuries__c from Course__c where id in :courseIDs]; //finds the relevant course record
    
    System.debug('The value of the course ID is: ' + courses);
    
    if(courses != null && courses.size() > 0)
    {
       for (Course__c c : courses)
       {
           System.debug('the value of number of injuries is: ' + c.Number_of_Injuries__c);
            c.Number_of_Injuries__c++;
       }
    }
    
    update courses;
PeteyBirdPeteyBird

Rookie mistake on the log - I must have somehow deleted myself as a monitored user.

 

Just tried entering "Illness" in the Type of Incident field and got an error, so need to learn about the Trigger.new and Trigger.old piece, as I'm assuming the issue is in my first if statement.

Jake GmerekJake Gmerek
I'm wondering if it could be this:

new Returns a list of the new versions of the sObject records.

Note that this sObject list is only available in insert and update triggers, and the records can only be modified in before triggers. <-- LOOK AT ME