0

This question already has an answer here:

I have an object that is having multiple child objects. I want to perform certain actions only if the current record has child records associated with it. For this I am checking the related list's size first, dynamically.But I am facing issues while saving my code :

for(Lead objLeadRec : lstLead) {
    for(LC_Setup_Map_Related_List__c objRelatedList1 : lstRelatedListRecords){
        relatedChildObjName = objRelatedList1.tdc_tlc__Child_Object__c.replace('__c','s__r');

        System.debug('relatedChildObjName'+relatedChildObjName);
        if(objLeadRec.relatedChildObjName.size() >0){
            hasRelatedListRecords = true;
        }
    }
}

I am facing issue on this line, since the list name which I want to query, I have created using a string ,

if(objLeadRec.relatedChildObjName.size() >0){

Can anyone suggest any workaround. Can't hardcode object names as this code belongs to a managed package and the object names can be different in different orgs.

marked as duplicate by Martin Lezer, battery.cord, Ratan Paul, Raul, Santanu Boral Jul 26 '17 at 15:09

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

1

To fetch the size of the child related list, use following as relatedChildObjName is of String type

if(objLeadRec.getSobjects(relatedChildObjName) != null && objLeadRec.getSobjects(relatedChildObjName).size() >0)

Use Null check to avoid Attempt to de-reference a null object error

Refer getSobjects

  • it has displayed the following error : Error: Compile Error: Method does not exist or incorrect signature: void size() from the type Object at line 95 column 68 – Shobhit Saxena Jul 26 '17 at 13:35
0

Sobject.getSobjects('child relationship name') is the way to get child list Please try the below code to dynamic fetch child related list and check size on it

if(objLeadRec.getSobjects(relatedChildObjName).size() >0)

For more reference please check the below URL https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_sobject.htm

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