I'm trying to create a trigger that will update a field on an account whenever the ownership of the account changes. I've tried to remove the NullPointerException error by adding if statements, but I'm still getting the same error and not sure what is going wrong. Any help would be fantastic!
trigger BusinessDivisionAccountOwnership on Account (after update)
{
Set<Id> relatedAccountIdSet = new Set<Id>();
for (Account acct : Trigger.new)
{
if (acct.Id != null)
{
relatedAccountIdSet.add(acct.Id);
}
}
Map<Id, User> relatedAccountsMap = new Map<Id, User>([SELECT Id
, Default_Business_Division__c
FROM User
WHERE Id IN :relatedAccountIdSet]);
for (Account newAcct : Trigger.new)
{
Account oldAcct = Trigger.oldMap.get(newAcct.Id);
if (oldAcct.ownerId != null)
{
if ((oldAcct.OwnerId != newAcct.OwnerId) && (newAcct.OwnerId != '00560000001NPSe') && (oldAcct.OwnerId != null) && (newAcct.OwnerId != null))
{
User newOwner = relatedAccountsMap.get(newAcct.OwnerId);
if (newOwner.Default_Business_Division__c != null)
{
newAcct.Business_Division__c = newOwner.Default_Business_Division__c;
}
}
}
}
}
Business_Division__c is the field I want to change on the account object, Default_Business_Division__c is a field on the account owner's page that I want it to pull from. I've also added logic to the trigger to prevent this change from occurring if our API user gains ownership.
Attribution to: grimsvotn
Possible Suggestion/Solution #1
You are adding the AccountId to the Set at the start instead of the OwnerId. This caused no users to come back in your query.
relatedAccountIdSet.add(acct.Id);
to
relatedAccountIdSet.add(acct.OwnerId);
Btw, this should be a before update trigger. Not after update.
Attribution to: dphil
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/33593