0

Is it possible when adding a lead via Apex code, to set the campaign that the lead belongs to?

I have a published app which retrieves lead data from an external API. The app can create a lead with standard fields set (first name, last name, etc).

In my app config settings I have added a field for the campaign name. The user will set this to the campaign which future created leads should be assigned to.

On this page https://help.salesforce.com/articleView?id=leads_fields.htm&type=5 it shows that the lead object has a campaign field, but in the developer console if I try and execute this query

SELECT Campaign FROM Lead

I am told that the no such column exists for Campaign. How can I assign a lead to a campaign?

Also, Is there a way (API or within SF) to see the fields in each object?

2

Campaign is a magic field, whose purpose is to aid in attaching a lead to a campaign on creation, both through the UI and web-to-lead. It is not a "real" field, and so cannot be used in Apex Code or the API. Instead, you need to simply insert a CampaignMember record to attach the Lead to the Campaign.

As for finding out which fields you can access, you would want to consult with the API documentation or your WSDL to see the fields available for each object. Note that the WSDL is affected by Field Level Security, so any fields you may have configured that you can't see won't appear in it.

Also, the Developer Console has a handy "see all fields" feature. Click on File > Open Resource, then type in the name of the object (e.g. Account.object) to see a list of fields.

  • Thanks for detailing the Campaign field and setting me in the right direction. Also +1 for the see all fields feature! – andrewb Mar 16 '18 at 14:19
1

Whenever you see a standard lookup, the field will have an API Name ending in ...Id. So if there were a direct lookup it would be CampaignId. However the relationship between Lead and Campaign is many-to-many, implemented using a child object to both called CampaignMember.

What you will have to do is something like:

Lead leadRecord = new Lead();
// fill in fields
insert leadRecord;

Campaign campaignRecord = [
    SELECT Id FROM Campaign
    WHERE Name = :leadRecord.Campaign_Name__c
];
CampaignMember member = new CampaignMember(
    LeadId=leadRecord.Id,
    CampaignId=campaignRecord.Id
);
insert member; 
  • Thanks. In my case, I do not have a custom field on the lead for campaign name. Rather, the campaign to assign lead to is held in a config setting, but this showed how to do it – andrewb Mar 16 '18 at 14:19

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.