Skip to content

Instantly share code, notes, and snippets.

@gdmarsh
Last active August 29, 2015 13:56
Show Gist options
  • Save gdmarsh/32cbed0f93e498606721 to your computer and use it in GitHub Desktop.
Save gdmarsh/32cbed0f93e498606721 to your computer and use it in GitHub Desktop.
Provides methods to retrieve ids from sobjects based on an arbitary field name
/**
* Provides methods to retrieve ids from sobjects based on an arbitary field
* name
* @author Gary Marsh
* @since 2014-01-23
*/
public class IdProvider {
/**
* Gets a set of ids from a list of sobjects based on the specified field
* name
* @param sObjects List of sobjects to get ids from
* @param fieldName Field name which represents the id
* @return Set of ids representative of field name
*/
public static Set<Id> getIds(final List<SObject> sObjects,
final String fieldName) {
Set<Id> ids = new Set<Id>();
for(SObject obj : sObjects) {
Id fieldId = getId(obj, fieldName);
if(fieldId != null) { ids.add(fieldId); }
}
return ids;
}
/**
* Gets an id based on a specified field name
* @param sObj Sobject to retrieve id from
* @param fieldName Field name which represents the id
* @return Id representative of field name
* @throws IdProviderException Throws exception if id is not a valid id
*/
private static Id getId(final SObject sObj, final String fieldName) {
Object fieldId = sObj.get(fieldName);
if(fieldId == null) { return null; }
if(isValidId(fieldId)) {
return (Id)fieldId;
} else {
throw new IdProviderException(fieldName + ' is not a valid id');
}
}
/**
* Checks to see if an object is a valid id
* @param test Object to test
* @return True or False
*/
private static Boolean isValidId(Object test) {
String testAsString = String.valueOf(test);
return (testAsString.length() == 15 || testAsString.length() == 18) &&
Pattern.matches('^[a-zA-Z0-9]*$', testAsString);
}
public class IdProviderException extends Exception {}
}
<?xml version="1.0" encoding="UTF-8"?>
<ApexClass xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>29.0</apiVersion>
<status>Active</status>
</ApexClass>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment