I have custom object called Referral__c. Referral__c has a lookup value for linking it to an Account. I am trying to get a count of all Referral__c records on each Account and populate a number field called Referrals__c on the Account.
I have the trigger below that compiles with no errors and seems to execute, but no updates occur on the Account field. When I look at the debug log, it tells me that the AccountId on the Referral__c object is null. What am I missing in my code?
trigger ReferralsCountTrigger on Referral__c (after insert, after update, after delete) {
Set<Id> setAccountIds = new Set<Id>();
if(Trigger.isInsert || Trigger.isUndelete)
{
for(Referral__c ref : Trigger.new)
{
setAccountIds.add(ref.Account__r.Id);
System.debug('@@@### - Account IDs'+ref.Account__r.Id);
}
}
if(Trigger.isDelete)
{
for(Referral__c ref : Trigger.old)
{
setAccountIds.add(ref.Account__r.Id);
System.debug('@@@### - Account IDs'+ref.Account__r.Id);
}
}
List<Account> listAccs = [SELECT Id,Referrals__c,(Select Id FROM Referrals__r)
FROM Account
WHERE Id in : setAccountIds];
System.debug('@@@### - Account List'+listAccs);
for(Account acc :listAccs)
{
acc.Referrals__c = acc.Referrals__r.size();
System.debug('@@@### - Referrals'+acc.Referrals__r.Size());
}
update listAccs;
}