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 the
Map<Id, Case> cases = new Map<Id, Case>();
for (CaseComment record : trigger.new)
if (record.ParentId != null)
cases.put(record.ParentId, new Case(Id=record.ParentId, Boo__c = true));
What's going on above?
- Take a collections based approach. You never want to perform queries or
DML Operations in a loop.
- In this case, two
CaseComment records could have the same
Case parent. Since you would get an error for trying to update the same record twice in a list, use a
- You can update a record without querying for it if you know its Id. In this case, you're basically updating
new Case(Id=caseId, CheckboxField__c=true).
- You need to actually update the records. You need to work with a
List<SObject> when making your
update call, hence the use of
If you want to filter on
RecordType as well, you will indeed need to query. In this case, you will want to first collect the
ParentId values that should be updated.
Set<Id> booCaseIds = new Set<Id>();
for (CaseComment comment : trigger.new)
if (comment.CommentBody != null && comment.CommentBody.containsIgnoreCase('boo'))
List<Case> records = [
SELECT Id FROM Case WHERE Id IN :booCaseIds
AND RecordType.DeveloperName = 'Some_Specific_RecordType'
for (Case record : records) record.Boo__c = true;
You should also look at An Introduction to Exception Handling and add proper exception handling to your code.