how to convert lead in apex

In this post we will see how to convert lead using apex. Many a times we may have to write a automated logic that has to convert the lead into Opportunity, account and contact
A lead when converted creates a account, contact and optionally an Opportunity. Mapping can be specified at set up --> Customise -- > Lead --> scroll down and click "Map Lead Fields""
Leads can be converted manually by pressing the button convert on lead detail page. We may need to do the process of conversion in apex class or trigger; for this Salesforce provides lead conversion method. The converted lead results are stored in database.leadconvertresult as shown in the below example. salesforce auto convert lead to contact , account and optional an account as shown in below example. Opportunity creation option is set using setDoNotCreateOpportunity parameter. In our case it is set to true that means no new opportunity will be created. Setting it to false would create a new opportunity

In the following example the lead is converted if the rating field has value "Hot".

1 comment:

  1. Hi Yoganand,

    When I try to execute the above code it throws me with the below error.

    Error: Compile Error: line 2:0 no viable alternative at character ' ' at line 2 column 0