0

How to refer Grand_Parent__c field in below if condition? I am trying to add parent ids to a collection type Set<>. But childObj.Parent__r.Grand_Parent__c value is not taking from grand parent though I have provided parent and grand parent values while testing manually.

public static void updateParent(List<Child__c>  childList){
        Map<ID, Parent__c> listLoan = new Map<ID, Parent__c>(); 
        List<Id> parentsetIds = new List<Id>();
        for (Child__c childObj : childList) {
            if(childObj.Parent__c != NULL && childObj.Parent__r.Grand_Parent__c != NULL){
                   parentsetIds.add(childObj.Parent__c); // here parentsetIds not taking childObj.Parent__r.Grand_Parent__c
               }
        }       
       // some logic
}
4

Triggers do not populate referenced objects, only the immediate fields of the objects themselves.

You, therefore, will need to execute a query to bulk load all the parent objects to access the grand parent details, like:

Set<Id> parentIds = new Set<Id>();

for (Child__c child : childList) {
    parentIds.add(child.Parent__c);
}

List<Parent__c> parents = [SELECT Id, Grand_Parent__c WHERE Id IN :parentIds AND Grand_Parent__c != NULL];

Map<Id, Parent__c> parentsById = new Map<Id, Parent__c>(parents);

// This is a set of all parents for the children that have a grandparent
parentIds = parentsById.keySet();

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.