0

I have this below method when I am passing fields dynamically to get passed object records.

relatedObjectName ==> Planner__c
recId ==> RecordId of Planner__c
fields = AccountPlanner__r.Email (Lookup to contact), Role__c (formula field of Planner__c object)

When I pass these values to below method, I am getting attempt to dereference null object at below line

string.valueOf(objectResult.fields.getMap().get(field).getDescribe().getType()) == 'REFERENCE' 

What is the way I can include related object fields and formula fields in Schema class.

public static List<sObject> getRecords(String recId, String fields, String relatedObjectName, 
                                           String conditions, String sortOrder, String relationship, String recordLimit, String offset) {
        
        List<sObject> relatedRecords = new List<sObject>();
        
        Id recordId = Id.valueOf(recId);
        Schema.SObjectType objectType = recordId.getSObjectType();
        String sObjectName = objectType.getDescribe().getName();
        DescribeSObjectResult objectResult = Schema.getGlobalDescribe().get(relatedObjectName).getDescribe();
        String finalFields = '';
        
        for (String field : fields.split(',')){
            system.debug('field ' + field);
            if (string.valueOf(objectResult.fields.getMap().get(field).getDescribe().getType()) == 'REFERENCE' ){
                finalFields = finalFields + ', ' + objectResult.fields.getMap().get(field).getDescribe().getRelationshipName() + '.Name' ;
            } else {
                finalFields = finalFields + ', ' + field;
            }
        }
        
        try{
            relatedRecords = Database.query(queryGenerator(finalFields.substring(1), relatedObjectName,recordLimit,offset, recordId,conditions,sortOrder));
            System.debug('RelatedRecords: ' + relatedRecords);
            
        }catch(Exception e){
            System.debug('Exception: '+ e);
        }
        
        return relatedRecords;
    }
5
  • 1
    Describing an Sobject only includes the fields on the object so only AccountPlanner__c and Role__c will be found
    – cropredy
    Commented Jul 6, 2021 at 14:08
  • ok .. So how to get AccountPlanner__r.Email fields? Is there any way Commented Jul 6, 2021 at 14:09
  • see getReferenceTo() and getRelationshipName() methods
    – cropredy
    Commented Jul 6, 2021 at 14:17
  • ok.. Do u have any examples ? Commented Jul 6, 2021 at 14:25
  • what real problem are you trying to solve? if you have in fields a list of valid field references, why do you need to use the Schema class to generate a query?
    – cropredy
    Commented Jul 6, 2021 at 23:28

0

You must log in to answer this question.

Browse other questions tagged .