[SalesForce] Setting the CampaignMember “Status” field in Apex

There seems to be a hole in my head today. I can't programmatically (in a test class in this case) set the "Status" field in a CampaignMember object.

Long and short is, I insert this in my test method:

new CampaignMember(CampaignId=testCampaign.Id, ContactId=contacts.get(i).Id, Status='Accepted')

but when I run the test, if I debug the CampaignMember object, I get this:

CampaignMember:{CampaignId=70124000000Hr3qAAC, Status=Sent, Id=00v24000000RxBmAAK, ContactId=00324000001p7w6AAA}

As you can see, status is remaining at the default "Sent"

I have read the docs

https://www.salesforce.com/developer/docs/api/Content/sforce_api_objects_campaignmember.htm

and noted some blogs that talk about how you have to set the "Text" value of the status (despite the fact it's a complicated picklist in the background).

There is an "Accepted" value in the Customise > Campaign > CampaignMember > Fields > Status configuration. I just don't seem to be able to make it stick? Anyone have any advice/input?

Best Answer

You need to create CampaignMemberStatus objects for your Campaign before you can assign them to CampaignMember objects for that Campaign.

Once you've done that your status changes should stick.

CampaignMemberStatus newStatus = new CampaignMemberStatus(
    CampaignID=campaign.id,
    Label='New',
    IsDefault=false,
    HasResponded=false,
    SortOrder=3
);

insert newStatus;

Ensure that your SortOrder is 3 or greater since 1 and 2 are taken up by the default 'Sent' and 'Responded' status values.

You will need to repeat this for every Campaign that you want this status for, this mimics using 'Advanced Setup' to set the statuses for a Campaign in the UI.

Related Topic