I'm trying to update a boolean field on Case
called Boo__c
when a new Case Comment
is added to the Case
and it contains the word boo
.
trigger OHT on CaseComment (before insert,before update) {
for(CaseComment c : Trigger.New) {
if(c.CommentBody.contains('boo'))
c.Parent.boo__c=true;
}
}
I'm getting the null pointer exception:
Apex trigger OHT caused an unexpected exception, contact your administrator: OHT: execution of BeforeInsert caused by:
System.NullPointerException: Attempt to de-reference a null object: ()
the field boo__c is on the Case object and I have access to it (I checked the Field Level Security)
What am I missing?
Best Answer
You can't just update related records in this way. You need to actually call
update
on a record. You can't access parent fields in a trigger context, but in this case you do not even need a query because you just need theParentId
.What's going on above?
DML Operations
in a loop.CaseComment
records could have the sameCase
parent. Since you would get an error for trying to update the same record twice in a list, use aMap<Id, Case>
.new Case(Id=caseId, CheckboxField__c=true)
.List<SObject>
when making yourupdate
call, hence the use ofvalues()
.If you want to filter on
RecordType
as well, you will indeed need to query. In this case, you will want to first collect theParentId
values that should be updated.You should also look at An Introduction to Exception Handling and add proper exception handling to your code.