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

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();
| improve this answer | |
  • 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 Sep 10 '18 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 Sep 10 '18 at 11:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.