Convert Lead Through Apex Salesforce

C

The following code automatically converts a lead into an Account/Contact, skipping creating an opportunity and redirects to the newly created Contact page.

Apex Class:

public class Nanostuffs_clsConvertLead
{
public PageReference convert()
{
try
{
String id = ApexPages.currentpage().getParameters().get('id');

Database.LeadConvert lc = new Database.LeadConvert();
lc.setLeadId(id);
lc.setDoNotCreateOpportunity(true);

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

Database.LeadConvertResult lcr = Database.convertLead(lc);
if(lcr.isSuccess())
{
String cId = lcr.getContactId();
PageReference redirect = new PageReference('/' + cId);
redirect.setRedirect(true);
return redirect;
}
}
catch(Exception e)
{
ApexPages.addMessages(e);
}
return null;
}

@isTest (seealldata=true)
public static void test()
{
Lead myLead = new Lead(LastName = 'Fry', Company='Fry And Sons', Email='sdf@sdf.com');
insert myLead;

myLead = [select Register_Student__c from Lead where Id=:myLead.Id];
myLead.Register_Student__c = true;
update myLead;

Nanostuffs_clsConvertLead c = new Nanostuffs_clsConvertLead();
ApexPages.currentPage().getParameters().put('id', myLead.Id);
c.convert();
}
}


Visualforce Page:

<apex:page controller="Nanostuffs_clsConvertLead" action="{!convert}">
<apex:pageMessages />
</apex:page>


Custom Url Button on Lead:

/apex/Nanostuffs_Custom_Lead_Convert?id={!Lead.Id}

About the author

Nishant Bamb
By Nishant Bamb

Category