Hi Guys !!!
Salesforce has given numerous functionality that we can use in the Standard way and get our job done but still, there are many areas in which we need to customize to achieve certain goals.
So today I am going to discuss one of such functionality that is Converting Lead through Apex.
At some stages, we get a requirement that at a particular Lead Status we need to convert the lead.
For this, you need an Apex Trigger and Apex Class
So below is the sample code snippet. You will have to add a new Picklist value to Status Field that is Verified.
Apex class :
public class leadtriggerhandler{ public class leadtriggerhandler
{
public void onafterupdate (list<lead>newList,map<id,lead>oldmap)
{
leadconvert(newList,oldmap);
}
public void leadconvert(list<lead>newList,map<id,lead>oldmap)
{ l
ist<Database.LeadConvert> leadstoConvert= new list<Database.LeadConvert>(); if(newList != null && newList.size()>0)
{
for(Lead objlead : newList)
{
try{
// Condition to check Whether Lead status is Verified or not
lead objlead_Old = oldmap != null ? (lead)oldmap.get(objlead.id) : null; if(objLead_Old != null && (objLead.Status != objLead_Old.status && objLead.Status == ‘Verified’&& !objlead.IsConverted))
{
Database.LeadConvert lc = new Database.LeadConvert();
// set lead id to convert
lc.setLeadId(objlead.Id);
LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true Limit 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
// this will not create Opportunity when converted through this. lc.setDoNotCreateOpportunity(true);
//This is will create Opportunity
//lc.setDoNotCreateOpportunity(false);
leadstoConvert.add(lc);
if(leadstoConvert != null && leadstoConvert.size()>0)
{
Database.LeadConvertResult[] lcr = Database.convertLead(leadstoConvert);
}
}
}
catch(exception e) {}
}
}
}
}
Apex trigger For this will be
trigger trgLeadConvert on lead (after Update)
{
if (trigger.isUpdate)
{leadtriggerhandler objleadTriggerHandler = new leadtriggerhandler();
objleadTriggerHandler.onafterupdate(trigger.new,trigger.oobjleadTriggerHandlerMap);
}
}
Hope this helps you !!!