Thursday, June 13, 2019

Accessing Parent Field Values from sObjects in Dynamic Queries Using Dynamic Apex

In case of dynamic queries, we often store queries output in sObject and then refer field values. In order to refer field values, we first type cast generic sObject into specific objects like Account, Contact or custom objects as mentioned below:

string qString = 'Select id, name from Account Limit 1';
sObject sb = database.query(qString);
Account acc = (Account)sb;
string accountName = acc.Name;

Suppose we know the field API names then we can utilize the concept of sObject to get field values directly without type casting as mention below:

string qString = 'Select id, name from Account Limit 1';
sObject sb = database.query(qString);
string accountName = sb.get('Name');

So now with the help of sObjects concept, we can access parent field values from child records.

Now consider a scenario in which I have list which stores all field API names which can be used to query opportunity line items. I will generate the dynamic query and will use concept of sObject to access Opportunity fields from sObject which is output of dynamic query.

List<string> fieldAPINamesList = new List<string>{'Id','Opportunity.Name','Opportunity.Partner__r.Name'};
string qString ='Select '+string.join(fieldAPINamesList,',')+ ' from OpportunityLineItem where id=\'00k90000002z4ml\'';
sobject sb = database.query(qString);
//syntax to get OpportunityLineItem Id  value from sObject
string OpportunityLineItemId = string.valueof(sb.get('Id'));
//syntax to get Opportunity.Name field value from sObject
string OpportunityName = string.valueof(sb.getSobject('Opportunity').get('Name'));
//syntax to get Opportunity.Partner__r.Name field value from sObject
//If partner field in opportunity is blank then you will get null pointer exception
string partnerName = string.valueof(sb.getSobject('Opportunity').getSObject('Partner__r').get('Name'));

Note: While accessing the parent record details in child to parent query, you will get null pointer exception if parent is blank in child record.

I have written an utility method which takes sObject and fieldAPIName as a parameter and returns field value. Please refer below code for reference:

If you run above script in developer console by specifying correct opportunityLineItem Id, then you will see below logs:

Hope this will help!!!

No comments:

Post a Comment