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;
}
AccountPlanner__c
andRole__c
will be foundgetReferenceTo()
andgetRelationshipName()
methodsfields
a list of valid field references, why do you need to use the Schema class to generate a query?