1

I am developing a functionality where I am to check for the presence of Child records, before executing a part of code. I can't do hardcoding since my code is going to be a part of a managed package, and object names may differ in the destination orgs.

I have child object's name and the lookup field stored in a custom setting, and I am thinking about storing the child relationship name to be stored in custom setting as well, which will be more helpful in fetching child's list size from Parent records query, rather than replacing '__c with 's__r' all the time, which may cause an issue in case the relationship name is different.

Is there any way using which we can fetch Child relationship name from the lookup field itself?

Here is the code I have tried so far...

for(Lead objLeadRec : lstLead) {
    //LC_Setup_Map_Related_List__c is the custom setting storing the details of the lookup fields with my Lead objects
    for(LC_Setup_Map_Related_List__c objRelatedList1 : lstRelatedListRecords){
        //relatedChildObjName is to get the child objects record count
        relatedChildObjName = objRelatedList1.tdc_tlc__Child_Object__c.replace('__c','s__r');
        System.debug('relatedChildObjName'+relatedChildObjName);
        //System.debug('objLeadRec.get(relatedChildObjName)'+objLeadRec.get(relatedChildObjName));
        if(objLeadRec.getSobjects(relatedChildObjName) != null && objLeadRec.getSobjects(relatedChildObjName).size()!=0){
            //hasRelatedListRecords is the boolean variable on the basis of which some part of code is to be executed
            hasRelatedListRecords = true;
        }
    }
}
2

No, you need to loop through the parent describe.

for (ChildRelationship relation : SObjectType.Lead.getChildRelationships())
    if (relation.getField() == MyObject__c.MyLookup__c)
        String relationshipName = relation.getRelationshipName();

You should do this processing before you enter your loop, not each iteration.

  • in that case, how would I be able to dynamically query for my object and field name as in the if statement of yours. Below is what I've tried, but its not allowing me to compare relation.getField() with String – Shobhit Saxena Jul 27 '17 at 8:35
  • for (ChildRelationship relation : SObjectType.Lead.getChildRelationships()) { for(LC_Setup_Map_Related_List__c objRelatedList : lstRelatedListRecords){ String sObjName = objRelatedList.tdc_tlc__Child_Object__c; String sObjField = objRelatedList.tdc_tlc__Lead_Field_on_Child__c; if (relation.getField() == sObjName.getField(sObjField)) { String relationshipName = relation.getRelationshipName(); } childObjName = '(SELECT Name FROM '+relationshipName+'),'; allChildRelationshipNames += childObjName; } } – Shobhit Saxena Jul 27 '17 at 8:36

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.