Skip to content

Instantly share code, notes, and snippets.

@ralphcallaway
Created February 18, 2013 23:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ralphcallaway/4981837 to your computer and use it in GitHub Desktop.
Save ralphcallaway/4981837 to your computer and use it in GitHub Desktop.
Recursive get
/*
Developer: Ralph Callaway <ralph@callawaycloudconsulting.com>
Description: Helper methods for dynamic DML
*/
public class DynamicDMLHelper {
public static Object recursiveGet(sObject record, String field) {
if(field.contains('.')) {
Integer firstPeriod = field.indexOf('.');
String nextObjectName = field.subString(0, firstPeriod);
String remainingfieldName = field.subString(firstPeriod + 1, field.length());
sObject nextObject = record.getSObject(nextObjectName);
if(nextObject == null) {
return null;
} else {
return recursiveGet(nextObject, remainingfieldName);
}
} else {
return record.get(field);
}
}
/* Test Methods */
@isTest
private static void testRecursiveGet() {
Account testAccount = TestUtil.createAccount();
Opportunity testOppty = TestUtil.createOpportunity(testAccount.id);
testOppty = [select account.name from Opportunity where id = :testOppty.id];
system.assertEquals(testAccount.name, (String) recursiveGet(testOppty, 'account.name'));
}
@isTest
private static void testRecursiveGetWithNullLookup() {
Case testCase = TestUtil.generateCase();
testCase.accountId = null;
insert testCase;
testCase = [select account.name from Case where id = :testCase.id];
system.assertEquals(null, (String) recursiveGet(testCase, 'account.name'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment