+ Start a Discussion
Robert Wambold 10Robert Wambold 10 

Creating CampaignMembers from Task when RelatedTo is a Campaign

Happy Friday All!

Our AEs don't always remeber to add CampaignMembers when they create Tasks related to the Campaign. To save the AEs and kepp marketing happy it was decided that we could use an Apex Trigger to check if the Contact was already a CampaignMember and add if they were not.

I think my code is close, but it is not adding the CampaignMember. Can someone please take a look at my code to show me what I missing?


Kind regards,


Robert.

 

trigger Task_to_CampaignMember on Task (after insert, before update) {

//WhoId is ContactId;
//WhatId is CampaignId;

  List<ID> WhoIds = new List<ID>();
  List<String> prStr = new List<String>();
  List<CampaignMember> newList = new List<CampaignMember>();

for(Task Tsk: Trigger.new){
    String WhtId = Tsk.WhatId;
    String CmpPfx = WhtId.substring(0,3);	 

    if(CmpPfx == '701') //'701' Prefix is Campaign
	{
		prStr.add(Tsk.WhatId); 
	}
}

  
Map<String,Id> cmMap = new Map<String,ID>();

for(CampaignMember cm1 :[select id,CampaignId,ContactId from CampaignMember where CampaignId IN: prStr])
{
	cmMap.put(cm1.CampaignId,cm1.Id);

}

for(Task Tsk: Trigger.new){
    if(Tsk.WhatId!=Null)

	{
		CampaignMember cm = new CampaignMember(CampaignId=Tsk.WhatId,ContactId=Tsk.Whoid,Status='Responded');
		newList.add(cm);
	}
}

if(newList.size()==0)
{
	insert newList;
}


}
Best Answer chosen by Robert Wambold 10
sfdcDeveloper 12sfdcDeveloper 12
In line 38 you have added if(newList.size()==0) instead of this it should be if(newList.size() > 0), it will work.
Also, you have not followed best practices.
 

All Answers

sfdcDeveloper 12sfdcDeveloper 12
In line 38 you have added if(newList.size()==0) instead of this it should be if(newList.size() > 0), it will work.
Also, you have not followed best practices.
 
This was selected as the best answer
Robert Wambold 10Robert Wambold 10

Thanks sfdcDeveloper12!

That did the trick for inserting new CampaignMembers. Now, I just need to prevent Duplicate_Value error

 

User-added image