+ Start a Discussion

Creating a generic related object map

Hi - not sure if this is the place to post this type of thing as it is not really a question, but more of a hope this helps others post.


I have found that I have needed to create a map of type Map<Id, Opportunity> in many triggers, so I decided to create a small method to genericize this type of behavior.   I'm sure this method can be genericized further so that it can create a map of any SObject, not just opportunity, but I just don't have the time to do that =)


Hope this helps others.  Would also gladly accept feedback on ways to improve the code as I'm not really a seasoned apex developer:


     * @description Return an opportunityMap for objects that
     * 				have a lookup or parent-child relationship to opportunity
     * @param sObjects the list of sObjects that have opportunity id
     * @param oppFieldName the field name that has the opportunity id
     * @param oppSelectFields the list of opportunity fields to select
    public static Map<Id, Opportunity> generateOppMap(List<SObject> sObjects, 
    		String oppFieldName, String[] oppSelectFields) {
    	Set<Id> opportunityIds = new Set<Id>();
    	for (SObject so : sObjects) {
    		if (so.get(oppFieldName) != null) {
    			opportunityIds.add((Id) so.get(oppFieldName));
    	// Prepare the select string
    	String selectString;
    	for (String oppField : oppSelectFields) {
    		oppField = oppField.trim();
    		if (selectString == null) {
    			selectString = String.escapeSingleQuotes(oppField);
    		} else {
    			selectString += ',' + String.escapeSingleQuotes(oppField);
    	String query = 'SELECT ' + selectString + ' FROM Opportunity ' +
    			'WHERE Id in :opportunityIds';
    	Opportunity singleOpp;
    	Opportunity[] opps;
    	if (opportunityIds.size() == 1) {
    		singleOpp = Database.query(query);
    	} else {
    		opps = Database.query(query);
    	if (opps == null) {
    		opps = new List<Opportunity>();
    	Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>();
    	for (Opportunity opp : opps) {
    		oppMap.put(opp.Id, opp);
    	return oppMap;





Ankit AroraAnkit Arora



Indeed it's a help but would request you to please post these kind of info on blogs or for even better you can post it as a cookbook recipe here:





Ankit Arora

Blog | Facebook | Blog Page


Thanks Wilard,it is really helpful.





The utility method you write has to be more generic than that to give a better bang for the buck.


Input parameters have to be only these 2 parameters


1) List<Id> opportunityIds - List of Opportunity Identifiers


2) String[] oppSelectFields - Array of Field names to Query


Return a Map of Opportunity Objects with requested Fields for the Opportunity Ids provided