0

I want to update a field on the related contacts of a campaign with a field of the related campaign when the campaing is updated. I can get the contactid trough CampaignMembers but how do I get the contact in a bulkified way?

I tried the following but this would mean I would have to query the current contact in the loop:

public static void updateRelatedContactFields(List<Campaign> newlist) {
        List<Campaign> campRelContact = [Select id, ACS__c , 
                                         (SELECT contactid  
                                          FROM CampaignMembers) FROM Campaign 
                                        WHERE id in :newlist];
        for(Campaign camp : campRelContact){
            for(CampaignMember c : camp.CampaignMembers){
                //get contact and update
            }
        }
    }

1 Answer 1

1

You'd place all the contact ID values into a map, then query the contacts, then continue with the rest of your logic:

    List<Campaign> campRelContact = [Select id, ACS__c , 
                                     (SELECT contactid  
                                      FROM CampaignMembers) FROM Campaign 
                                    WHERE id in :newlist];
    Map<id, contact> contacts = new map<id, contact>();
    for(Campaign record: campRelContact) {
      for(CampaignMember member: record.CampaignMembers) {
        contacts.put(member.contactid, null);
      }
    }
    contacts.putall([select id from contact where id = :contacts.keyset()]);
    for(Campaign record: campRelContact) {
      Contact c = contacts.get(record.contactid);
      c.somefield__c = somevalue...;
    }
    update contacts.values();
2
  • Thanks for the answer. Is there like a rule to recognize when to use a map? The answer needs to be updates with for(Campaign record : campRelContact) { for(CampaignMember member: record.CampaignMembers) { Contact c = contacts.get(member.contactid); c.ACS__c = record.ACS__c; } }
    – Thomas
    Commented Sep 10, 2018 at 11:27
  • @Thomas In the general case, you need a map when there might be more than one record with the same ID.
    – sfdcfox
    Commented Sep 10, 2018 at 11:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .