[SalesForce] How to access values from Map

I created a map of , following is the query to create map.

map <string, Campaign> ExpenseCampaignMap = new map <string, Campaign>([select Id,                   
                                                                         UtmCampaign_ID__c 
                                                                         from Campaign
                                                                        where UtmCampaign_ID__c in :UTMCampaignId]);

Where UTMCmapaignId is a set of string, where values are added from trigger.new

for(Contact con: trigger.new)
    {
        CampaignExternalId.add(con.Source_Campaign__c);
        UTMCampaignId.add(con.utmcampaign__c);
    }

I am trying to create a campaing member for the campaigns in the map, using UTMCampaign_ID__c, which is an external ID on campaign.

Following is the code to create campaign members

 list<CampaignMember> newCampaignMembersExpCamp = new list<CampaignMember>();
 Campaign UTMCampaign;  

  for(Contact con: trigger.new)
    {
        system.debug('Contact UTM Campaign id  ' + con.utmcampaign__c);

        UTMCampaign = ExpenseCampaignMap.get(con.utmcampaign__c);

        system.debug('UTM Campaign id  ' + UTMCampaign);

        CampaignMember cm= New CampaignMember(CampaignId=UTMCampaign.Id, ContactId= con.Id ,LeadId= null, Status='Opt-In');
        newCampaignMembersExpCamp.add(cm);
    }
insert newCampaignMembersExpCamp;

However, the get() satement for map is not returning anyvalue. UTMCmapign is null. I am not sure how to get value of the campaign from map based on the string key.

Best Answer

This code...

map <string, Campaign> ExpenseCampaignMap = 
   new map <string, Campaign>(
     [select Id, UtmCampaign_ID__c 
        from Campaign
        where UtmCampaign_ID__c in :UTMCampaignId]);

Results in your Map being keyed by the Id field not the value of your UtmCampaign_ID__c field value.

So the following code will only work if utmcampaign__c on your Contact object contains an actual Campaign record Id or is a Lookup field to Campaign.

UTMCampaign = ExpenseCampaignMap.get(con.utmcampaign__c);

You need to populate your Map using the UtMCompaign_ID__c not the Id. Unfortunatly this has to be done manually by iterating over the results of the query like so...

List<Campaign> ExpenseCampaignList = 
     [select Id, UtmCampaign_ID__c 
        from Campaign
        where UtmCampaign_ID__c in :UTMCampaignId];
Map<string, Campaign> ExpenseCampaignMap = new map <string, Campaign>();
for(Campaign c : ExpenseCampaignList)
    ExpenseCampaignMap.put(c.UtmCampaign_ID__c, c);
Related Topic