Monday, April 6, 2015

Convert Lead using Custom Button

To create a custom button for Lead Go Setup > Build > Customize > Lead > Buttons, Links, and Actions

Custom Button Code

{!REQUIRESCRIPT("/soap/ajax/33.0/connection.js")}
{!REQUIRESCRIPT("/soap/ajax/33.0/apex.js")}

var r = confirm("Converting this Lead will create Account, Contact and Opportunity? Are you sure you would like to do this?");

if (r == true) {

   var leadToUpdate = new sforce.SObject("Lead");
   leadToUpdate.Id = "{!Lead.Id}";

   var result = sforce.connection.update([leadToUpdate]);
   
   var l = "{!Lead.Id}";
   var q = sforce.connection.query(
   "Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1");
   
   records = q.getArray("records");
   var record = records[0].MasterLabel;

   var convert = new sforce.LeadConvert();
   convert.leadId = l;
   convert.convertedStatus = record;
   
   result = sforce.connection.convertLead([convert]);

   if (result[0].getBoolean("success")) {
      var o = result[0].accountId;
      window.location.href="/"+o;
   } 
   else {
      alert("Sorry Unable to convert Lead that is in use by workflow.")
   }

}