2

Many of the questions that I searched for on here deal with converting a Lead to either an existing account or contact.

My requirement is that I convert the lead to a new opportunity. This logic needs to be handled dynamically/automatically in Apex.

Most of the code snippets that I come across this look something like this:

Database.LeadConvert leadConvertObj = new database.LeadConvert(); leadConvertObj.setLeadId(lead.Id); leadConvertObj.setDoNotCreateOpportunity(true); //This looks like the Boolean parameter WILL NOT create an opportunity

            LeadStatus convertStatus = [SELECT Id, MasterLabel
                                        FROM LeadStatus
                                        WHERE IsConverted = true
                                        LIMIT 1];
            leadConvertObj.setConvertedStatus(convertStatus.MasterLabel);

            Database.LeadConvertResult leadConvertResult = Database.convertLead(leadConvertObj);
            System.assert(leadConvertResult.isSuccess());

I want something like leadConvertObj.setCreateOpportunity();. Please note that I want to convert the lead into a NEW opportunity.

2
  • Could you clarify what your goal is? A Opportunity can't exist without an account if you try to achieve this.
    – Nina Rosen
    Commented Oct 15, 2020 at 8:23
  • I am trying to convert a lead into an opportunity when a simple condition is met. How can I achieve this. If I need to get the account ID then may you assist with a solution? Commented Oct 15, 2020 at 9:16

1 Answer 1

3

Just to be clear: when a lead is converted, three objects result - Account, Contact, and Opportunity. The last one is optional, but is the default behavior.

See the docs for the lead convert class: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_dml_convertLead.htm

The above includes methods like isDoNotCreateOpportunity(), which defaults to False. Another helpful method would be setOpportunityName(opportunityName)

So, basically, by default you can create an opportunity and default its name. If you need to update other fields, you'll have to do the convert and then retrieve the new opportunity via SOQL.

Something like this:

Lead myLead = new Lead(LastName = 'Fry', Company='Fry And Sons');
insert myLead;
 
Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(myLead.id);
 
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
lc.isDoNotCreateOpportunity(false); 
lc.setOpportunityName('New Opportunity Name Here');
 
Database.LeadConvertResult lcr = Database.convertLead(lc);
System.assert(lcr.isSuccess());

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .