0

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;
}

1 Answer 1

3

You do not have access to a populated ref.Account__r.Id field in this context. That's a field on the other side of a relationship, which is never populated for you in a trigger context and requires you to query. It will appear as null here.

Instead, you should always use ref.Account__c, which is populated on this object.

1
  • Ah, thanks so much!
    – J. Neilan
    Commented Oct 10, 2020 at 20:20

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .