Sunday, 30 November 2014

Accessing parent object field in trigger Salesforce!!

Hi Guys!

It is Saturday out here and am sharing a few rodablocks you may face while executing your code. Beware , if you are new to salesforce apex like me. It can take days and hours, to solve the issue which I will discuss with you.

Some good readers may be aware of it already. Ok

Issue:- I was working in my office and doing debugging of a trigger which someone wrote a year back I guess. But I got an scenario that this trigger is not working properly means it is doing 95 5 of its work. But rest 5 % was the bug.

So lemme explain you the scenario. Say, I have two two custom object A  and B . Also I have a USER object.

Lets go with the rlation ship User is the parent of 'A' object. In turn 'A' is the parent of 'B' object.
As we know that there is a field called Manager on User object which is lookup field to user. So, whenever a record of object'A' is created then the manager of parent A should be replicated to a field Manager__B on Custom Object'B'. Obviously we have trigger on Custom Object'A' . But catch here is you cannnot use the value of a parents fields directly. you need to querry that field. Lemme share you with the codesinppet.


for(custom__A res: [Select Id,  custom__A__User__r.ManagerId from custom__A where Id in:resIds ]){
                custom__B mem = resourceToMemberMap.get(res.Id);
                mem.OwnerId = res.OwnerId;
                mem.Line_Manager__c = res.custom__A__User__r.ManagerId;                

You cannot  use the value res.custom__A__User__r.ManagerId untill this field is being used in query.
So, you need to query this field. Otherwise you ll get mem.Linemanager = null always.

Credit for this learning goes to my colleques and to the Senior developer who passed on this piece of knowledge to me .

Cheers
happy coding!

Thanks
Ankush












No comments:

Post a Comment

oAuth Use Case -  Headless API Explained in the Easiest way Wondering why? and When we use the Headless API flow Use case example: Imagine a...