You need to sign in to do that
Don't have an account?
Null pointer exception on Task Trigger (banging my head against the wall - please help)
Summary:
My trigger is supposed to update a custom field on the related Account called Owner_s_Last_Activity_Date__c with the CreatedDate of the Task any time a new task created on the Account is assigned to the Account owner. The trigger works great in the positive case (i.e. the Related Account lookup is populated), but I'm getting a null pointer exception any time the related Account lookup is null. I know I need to filter tasks with no related Account out of my trigger logic, but I just can't seem to figure out how to do it. Any help would be greatly appreciated. Thanks!
trigger UpdateAccountFromActivity on Task (after insert) {
Map<ID, Account> parentAccts = new Map<ID, Account>();
List<Id> listIds = new List<Id>();
for (Task task : Trigger.new){
if(task.AccountId!=null)
listIds.add(task.AccountId);
}
parentAccts = new Map<Id, Account>([SELECT ID, Owner_s_Last_Activity__c, OwnerID, (SELECT ID, CreatedDate, OwnerId, AccountID FROM Tasks WHERE AccountID!=null ) FROM Account WHERE ID IN :listIds]);
for (Task task: Trigger.new){
Account myParentAcc = parentAccts.get(task.AccountId);
if(myParentAcc.OwnerId == task.OwnerId && task.AccountID != null){
myParentAcc.Owner_s_Last_Activity__c = task.CreatedDate;
}
}
update parentAccts.values();
}
All Answers
please replace the code section with the below given code.
for (Task task: Trigger.new){
if(task.AccountId != null){
Account myParentAcc = parentAccts.get(task.AccountId);
if(myParentAcc.OwnerId == task.OwnerId && task.AccountID != null){
myParentAcc.Owner_s_Last_Activity__c = task.CreatedDate;
}
}
}