Skip to content

Instantly share code, notes, and snippets.

@mhamzas
Created April 30, 2021 09:50
Show Gist options
  • Select an option

  • Save mhamzas/8803a6a4facb19ab437ae2d5fc43c5e3 to your computer and use it in GitHub Desktop.

Select an option

Save mhamzas/8803a6a4facb19ab437ae2d5fc43c5e3 to your computer and use it in GitHub Desktop.
Accessing Parent Field Values from sObjects in Dynamic Queries Using Dynamic Apex
/*------------Accessing parent field values in child to parent dynamic query----//
//Below is static method which can be used to fetch field values.//
//You need to pass sObject and fieldAPIName to get field value---*/
// CREDITS: https://www.sfdcstuff.com/2019/06/accessing-parent-field-values-from.html
public static string ExtractFieldValues(sObject sb, string fieldAPIName) {
string fvalue = '';
if (fieldAPIName.contains('.')) {
List < string > splitedFields = fieldAPIName.split('\\.');
try {
for (integer i = 0; i < splitedFields.size() - 1; i++) {
sb = sb.getSobject(splitedFields[i]);
}
fvalue = string.valueof(sb.get(splitedFields[splitedFields.size() - 1]));
} catch (exception ex) {
system.debug('******exception while fetching fieldValues as relationship ' + fieldAPIName + ' value is blank.' + ex.getmessage());
fvalue = '';
}
} else if (sb.get(fieldAPIName) != null) {
fvalue = string.valueOf(sb.get(fieldAPIName));
}
return fvalue;
}
List < string > fieldAPINamesList = new List < string > {
'Id',
'Opportunity.Name',
'Opportunity.Partner__r.Name',
'Product2.Name'
};
string qString = 'Select ' + string.join(fieldAPINamesList, ',') + ' from OpportunityLineItem where id=\'00k90000002z4ml\'';
system.debug('****qString:' + qString);
sobject sb = database.query(qString);
//syntax to get OpportunityLineItem Id value from sObject
string OpportunityLineItemId = string.valueof(sb.get('Id'));
system.debug('******OpportunityLineItemId:' + OpportunityLineItemId);
//syntax to get Opportunity.Name field value from sObject
string OpportunityName = string.valueof(sb.getSobject('Opportunity').get('Name'));
system.debug('******OpportunityName:' + OpportunityName);
//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'));
system.debug('******partnerName:' + partnerName);
//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.
//Below is sample code to get field values by using utility method defined above
for (string fieldName: fieldAPINamesList) {
string fieldvalue = ExtractFieldValues(sb, fieldName);
system.debug('******fieldvalue using utility method:' + fieldvalue);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment