In the Force.com Explorer I can perform the following query:
SELECT Id, (SELECT Id,LeadId,ContactId FROM CampaignMembers) FROM Campaign
It displays every campaign.Id in one column and the next column has a list of campaignmembers associated with the campaign.
If my example code below is incorrect please feel free to correct it. I am still new to apex coding.
I need to create a Campaign map that is as follows where first parameter of Map is CampaignId:
Map<Id, List<Id,CampaignMember>> newMap = new Map<Id, List<Id, CampaignMember>>();
List<Id> cntList = new List<Id>;
List<Id> leadList = new List<Id>;
for(CampaignMember mem: memberList){
if(mem.LeadId != null )
leadList.add(mem.LeadId)
else if (mem.ContactId != null)
cntList.add(mem.ContactId);
}
List<CampaignMember> newCms = new List<CampaignMember>();
//assuming new map is correct format and is filled in
For(Campaign cmp : campList) {
List<CampaignMember> cmMems = newMap.get(cmp.Id);
//check if lead/contact is a campaign member, if not make the lead a campaign member
//the lead/contact records below are just to show you that i am getting a lead or contact associated with campaign members
Lead ld1 = [Select Id From Lead Where Id IN: leadList Limit 1];
Contact cnt1 = [Select Id From Contact Where Id IN: cntList Limit 1];
if(ld1 != null)
//leads is not associated with campaign member so it will be added
if( !(cmMems.contains(ld)) )
CampaignMember newCm = new CampaignMember(CampaignId=cmp.Id, LeadId=ld1.Id);
newCms.add(newCm);
else if (cnt1 != null)
//contact is not assocaited with a campaign member so it will be added
if( !(cmMems.contains(cnt1)) )
CampaignMember newCm = new CampaignMember(CampaignId=cmp.Id, ContactId=cnt1.Id);
newCms.add(newCm);
}//end for