You need to sign in to do that
Don't have an account?
cmaine3
Task Trigger Works Under Opp Only
Hi there-
So I got assistance on this code, built the test class and deployed it. It works fine when creating a Task under Opp but throws a null pointer exception error when I create a task under any other object.
Goal: When adding a task in opportunity automatically pull the assigned rep and select the picklist field for them on the task. When no rep selected do nothing.
Both fields are named Assigned_Rep__c, however the field on the Opp is a reference Assigned_Rep__r.Name. I do not need any trigger except when accessed from an opportunity.
Error:
Attempt to de-reference a null object Trigger.populatePicklist: line 9, column 34
Trigger
trigger populateAssignedRep on Task(before insert, before update){ String oppPrefix = Schema.SObjectType.Opportunity.getKeyPrefix(); List<Id> oppIds = new List<Id>(); for(Task t: Trigger.new){ String relatedTo = (String)t.WhatId; String relatedToPrefix = relatedTo.subString(0,3); if(oppPrefix == relatedToPrefix){ oppIds.add(t.WhatId); } } Map<Id,Opportunity> oppMap = new Map<Id,Opportunity>(); if(!oppIds.isEmpty()){ oppMap.putAll([Select Id, Name, Assigned_Rep__c, Assigned_Rep__r.Name from Opportunity where Id IN :oppIds]); for(Task t: trigger.new){ String relatedTo = (String)t.WhatId; String relatedToPrefix = relatedTo.subString(0,3); if(oppPrefix == relatedToPrefix){ if(oppMap.containsKey(t.WhatId)){ Opportunity opp = oppMap.get(t.WhatId); if(opp.Assigned_Rep__c != null){ t.ARI_Rep__c = opp.Assigned_Rep__r.Name; } } } } } }
I'm using this as my first venture into triggers, and was able to handle the test class by myself, so I am extremely appreciative of the help I am getting. Thanks everyone.
I've recreated your trigger into our sandbox and only issue i had was in case the task wasn't assigned to anything, which after all is quite logic as the WhatId value is then NULL. With the change below everything should be fine.
Cheers,
Fred
All Answers
Hi,
The issue is not related to this trigger, the error msg state it's Trigger.populatePicklist which gives a NPE.
When looking at your code I don't see any potential issues, and it will only fire when creating a task on opportunity.
Kr,
Fred
Sorry- I hand typed that in and it should be Trigger.populateAssignedRep. The error is still on in the same position on that trigger. Thanks for catching my typo, but the error is still on this trigger.
I've recreated your trigger into our sandbox and only issue i had was in case the task wasn't assigned to anything, which after all is quite logic as the WhatId value is then NULL. With the change below everything should be fine.
Cheers,
Fred
Thanks Frederic, that did the trick!