I'm trying to write some APEX to get the Owner of an Account (Account__c) referenced by a Lead and set that Owner as the Lead Owner.
I'm running into an error where the variable contains a null value, but I'm not seeing why.
Relevant portions of code below.
Trigger:
trigger LeadTrigger on Lead (before insert, before update, after insert, after update) {
if (trigger.isBefore && (trigger.isInsert || trigger.isUpdate)) {
System.debug('Starting LeadHelper.companyLeadAccountChange');
LeadHelper.companyLeadAccountChange(trigger.new, trigger.oldMap);
System.debug('Ending LeadHelper.companyLeadAccountChange');
}
}
Class:
public static void companyLeadAccountChange (list<Lead> company, map<Id, Lead> mapCompany) {
If (company != null && !company.isEmpty()){
For(Lead i : company){
System.debug('Account: '+i.Account__c+', Account Owner (lead relation): '+i.Account__r.OwnerId+', Account Owner (account lookup): '+[SELECT Id, Name, OwnerId, Owner.Name
FROM Account
WHERE Id =:i.Account__c]);
If(i.recordTypeId == Util.getRecordTypeId('Lead','Client') &&
i.Account__c != NULL &&
(trigger.isInsert || (trigger.isUpdate &&
i.Account__c != mapCompany.get(i.Id).Account__c))){
System.debug('Current: ' + i.OwnerId + ', New: ' + i.Account__r.OwnerId);
i.OwnerId = i.Account__r.OwnerId;
}
}
}
}
Here are some of the debug lines:
USER_DEBUG|[123]|DEBUG|Account: 001M000000dFYdvIAG, Account Owner (lead relation): null, Account Owner (account lookup): (Account:{Name=Test, OwnerId=005M0000005zikzIAA, Id=001M000000dFYdvIAG})
USER_DEBUG|[132]|DEBUG|Current: 00GC0000002BekVMAS, New: null
For some reason, the lead's Account__c field is returning a value, but looking through the relationship lookup returns a null owner of that Account. You can see in the Debug that the Query returns an owner of that specific record. Can anyone identify why the account returns owner ID when queried but returns null when using the relationship reference? Should I just use the i.Account__c to instantiate an account record and get the ownerId that way?