0

I've got the following code snippet in a trigger handler class

x1 = trigger.new;
List<Id> listx = new List(Id);

    For(integer i = 0; i < x1.size(); i++ ) {

         System.debug('Loop run:'+ i);    

                listx.add(x1[i].Ben_Loan__r.id);

          }

System.debug('listx:' + listx );

In the debug logs, 'listx' is shown as null even though it should work. Ben_Loan__r.id is the id of a look up field.

When I try a different For Loop as below, I still get an error "Variable id does not exist".

   For(List <Beneficiary_Loan_Repayment__c> LX1 : x1){
            listx.add(LX1.Beneficiary_Loan__r.id);
}

Any idea what the issue could be? Thanks in advance

4

You cannot access related fields in trigger context, only fields on the object that is in transaction can be accessed. If you want to access related fields, you will have to query it explicitly. If you try to access relationship fields in trigger context, it will return null, hence your list is showing null.

In your case, as you are accessing the ID field, you can access directly using the lookup field instead of using relationship field.

You can replace this below code

listx.add(x1[i].Ben_Loan__r.id);

with

listx.add(x1[i].Ben_Loan__c);

Similarly, you can replace below code if its a lookup field

listx.add(LX1.Beneficiary_Loan__r.id);

with

listx.add(LX1.Beneficiary_Loan__c);
  • Thanks, this worked (listx.add(x1[i].Ben_Loan__c)) but listx.add(LX1.Beneficiary_Loan__c); didn't work – Rufus K. May 20 '19 at 10:52
  • I don't think Beneficiary_Loan__c is a lookup field, if it would have been a lookup field, then the compiler wouldn't have given the error Variable id does not exist. You can traverse through to the parent only via lookup/master detail fields. – Vijay Ganji May 20 '19 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.