You need to sign in to do that
Don't have an account?

Not able to Add CampaignMembers to Campaign :(
Campaign[] c = [Select ID From Campaign Where Name = 'Customer Communication']; if (c.size() > 0) { CampaignMember[] toAdd = new CampaignMember[] {}; CampaignMember[] toDel = [Select ID From CampaignMember Where CampaignId =: c[0].Id]; for (Contact co : [Select ID From Contact Where AccountId IN (Select Account__c From Subscription_Contracts__c Where Status__c = 'Current') And Email != null]) { CampaignMember cm = new CampaignMember(); cm.CampaignId = c[0].Id; cm.ContactId = co.Id; toAdd.add(cm); system.debug('\n@@toAdd : '+cm); } if ( !toDel.isEmpty() ) delete toDel; if ( !toAdd.isEmpty() ) insert toAdd; }
Above is my code to Clean the Campaign and then Add the CampaignMembers to it again. but it is causing following Exception on "insert toAdd" line:
System.DmlException: Insert failed. First exception on row 100; first error: DUPLICATE_VALUE, This entity is already a member of this campaign: [] clsUpdateMarketingCampaigns.cls
I don't see how can there be a duplicate entity, can anyone please help me point out erroreneous code which I might be doing wrong here? plz.
I don't see the point of your code, but you seem to be selecting CampaignMembers just for one campaign for deletion, whereas you're attempting to add them for all Campaigns selected
Your query:
Is probably returning the same account multiple times. Therefore you insert has duplicate contacts.
A quick fix is to add the contact ID to a set to make sure they are unique, but I would consider reengineering your code a bit.
No that didn't worked either.
The business purpose of my code is to Refresh CampaignMembers in a Particular Campaign. So I first fetch all Existing Members of the Campaign, and then Delete those members. Then I fetch all Contacts from my system based on a query, such that I need to fetch all Contacts whose Accounts exist in another system, for that I don't see any flaw in my query:
In this query, it will return all Unique Contacts, I don't see how there could be a duplicate ID of a contact returned from a single Query, UNLESS, salesforce verified Duplicates based on ACCOUNTID ??? .. Is this the problem? Can 2 Contacts with Same AccountID be added to a Campain OR NOT?