salesforce lead conversion

This application allows user to search leads based on a keyword and giving fields to search in. User can then go to details page of returned leads, can select multiple leads and then can convert selected leads by providing an account name.  The Outcome will be an account, a contact for each lead and an opportunity for each lead. After successful conversion user will be redirected to newly created account’s detail page.

Video Url:

http://www.screencast.com/users/vishesh91/folders/Default/media/5e12fd28-ba37-4e95-8eea-e3c89f0c1ad5

you can install the unmanaged package from :

https://login.salesforce.com/packaging/installPackage.apexp?p0=04t90000000Q3Ww

App uses one visual force page and one controller :

<apex:page controller="ConversionController">
    <script type="text/javascript">
           //user can select which all fields to search like name,address,email
           //All fields will be selected by default
        
         function checkAllFields(){ //to select all fields on page load
            var inputElem = document.getElementsByTagName("input"); //get all input elements
            for(var i=0; i<inputElem.length; i++)
            {    
                 if(inputElem[i].id.indexOf("searchFields")!=-1)   //check for inputBoxes to select search fields                      
                   inputElem[i].checked = true; //check all fields initially
            }
          }
          
          function checkAllLeads(cb){  //to implement select all function for all leads returned by search
            //cb is the select all check box,which will be passed to this function
            var inputElem = document.getElementsByTagName("input"); //get all input elements
            for(var i=0; i<inputElem.length; i++)
            {    
                 if(inputElem[i].id.indexOf("leadCheckBox")!=-1)   //check for inputBoxes to select leads                   
                   inputElem[i].checked = cb.checked; //check or uncheck according to select all checkBox
            }
          }
          
          function makeLinks(){   //to render labels of lead select boxes as links for corresponding leads
            var inputElem = document.getElementsByTagName("label"); //get all labels
            for(var i=0; i<inputElem.length; i++)
            {    
                  var myCheckBoxId=inputElem[i].getAttribute("for");  //get Id of associated element
                  if(myCheckBoxId!=null && myCheckBoxId.indexOf("leadCheckBox")!=-1)   //only change labels for lead select boxes                     
                          {  var leadId=document.getElementById(myCheckBoxId).getAttribute("value"); //get the lead Id from corresponding checkBox
                             //change the inner html of label accordingly
                             //links will be like https://ap1.salesforce.com/leadId
                             //instance is auto corrected by Force.com if not ap1
                             inputElem[i].innerHTML ='<apex:outputLink value="https://ap1.salesforce.com/'+leadId+'" target="_blank">'+inputElem[i].innerHTML+'</apex:outputLink>';
                          }
            } 
          }
          
     </script>
    
     <apex:form>
      <apex:pageblock mode="edit">
         <apex:pagemessages id="messages">  
         
         <apex:pageblocksection title="Search" columns="3">
            <apex:outputlabel>Enter Keyword</apex:outputlabel>
            <apex:inputtext value="{!keyword}">
            

            <apex:outputlabel>Search Fields</apex:outputlabel>
            <apex:selectcheckboxes value="{!searchIn}" id="searchFields">
                           <apex:selectoption itemvalue="name" itemlabel="Name">
                           <apex:selectoption itemvalue="street" itemlabel="Address">
                           <apex:selectoption itemvalue="email" itemlabel="Email">  
                           <!-- more options can be added here without any other change in the code -->
            </apex:selectoption></apex:selectoption></apex:selectoption></apex:selectcheckboxes>
            

            <apex:commandbutton value="Search" rerender="leadDisplay,messages" status="waitMessage">
         
         </apex:commandbutton></apex:inputtext></apex:pageblocksection>
         
         <apex:pageblocksection title="Leads" columns="1" id="leadDisplay">
            <apex:outputlabel escape="false"><i>Lead Displayed as Name(Company) , Follow the link to go to lead's Details page</i></apex:outputlabel>
            <apex:inputcheckbox label="Select All" onclick="checkAllLeads(this)">
           
            <apex:actionstatus id="waitMessage">
            <!-- showing animation by searching and rendering search results -->
               <apex:facet name="start">
               <!-- custom controller 'loading',uses resource 'loading' which is a gif image -->
                    <c:loading backcolor="#efefef" bordercolor="#336699" bordersize="3" height="50px" width="120px" imageurl="{!$Resource.loading}" message="Loading..." messagestyle="color:darkred;font-size:11pt;
                         font-weight:bold;">
               </c:loading></apex:facet>
            
               <apex:facet name="stop">
                    <apex:selectcheckboxes value="{!leadIdsToConvert}" layout="pageDirection" id="leadCheckBox">
                        <apex:selectoptions value="{!leads}">     
                    </apex:selectoptions></apex:selectcheckboxes>
                    
               </apex:facet>
            </apex:actionstatus>
            <!-- render select boxes' labels as links to corresponding leads -->
            <script>makeLinks();</script>
         </apex:inputcheckbox></apex:pageblocksection>
         
         <apex:pageblocksection title="Convert Leads">
            <apex:outputlabel>Enter Account Name</apex:outputlabel>
            <apex:inputtext value="{!accountName}">
            <apex:commandbutton value="Convert Leads" action="{!convertLeads}">
         </apex:commandbutton></apex:inputtext></apex:pageblocksection>
         
      </apex:pagemessages></apex:pageblock>
     </apex:form>
     <script>
       checkAllFields(); //check all search fields on page load
     </script>
   
</apex:page>


Controller :

public with sharing class ConversionController {

    public String[] searchIn =new String[]{};  //array containing field names to search like name,address,email
    public String keyword { get; set; }   //keyword to search in given fields
    public String[] leadIdsToConvert =new String[]{};  //Ids of leads checked by user to convert
    public String accountName{get; set;}   //name of the account to be created,given by user 
    
    public void setSearchIn(string[] searchIn) {
      this.searchIn=searchIn;
    }
    
    public String[] getSearchIn() {
      return searchIn;
    }
    
    public void setleadIdsToConvert(string[] leadIdsToConvert) {
      this.leadIdsToConvert=leadIdsToConvert;
    }
    
    public String[] getleadIdsToConvert() {
      //We don't want any lead to be selected by default,so clear leadIdsToConvert array.   
      leadIdsToConvert.clear();
      return leadIdsToConvert;
    }
    
    public List<SelectOption> getLeads() { //returns leads based on search criteria
        
        String myQuery='Select Id,Name,Company From Lead where isConverted=false';  //only give leads which can be converted
        //filter according to search criteria
        
        //show all convertible leads on first load or
        //If user gives no keyword(keyword='') or no field to search in(searchIn.size()=0) 
        if(keyword!=null && keyword!='' && searchIn.size()!=0)
         {  //we want to create myQuery like
            //Select Id,Name From Lead where isConverted=false and (name like '%value%' or email like '%value%' or..........) 
            String prefix=' and (';  //to be prefixed with first filter to myQuery
           //now add all fields to search in
           for(String field:searchIn)
             {
              myquery=myquery+prefix+field+ ' like \'%'+keyword+'%\'';
              prefix='OR '; //if a field has been added next field should be prefixed by OR
             }
           //all fields added,so close the parenthesis after and
           myquery+=')';
             
         }
         
        List<SelectOption> options = new List<SelectOption>(); //leads will be returned as select options,which will be displayed as checkBoxes
         
        for(Lead l:database.query(myquery))
                options.add(new selectOption(l.Id,l.Name+'  ('+l.Company+')')); //add all queried leads to SelectOption array
        
        return options;
    }
    
    public PageReference convertLeads() { //converts selected leads and redirects to newly created account
        if(leadIdsToConvert.size()==0) //give error if no lead selected to convert
           {Apexpages.addMessage( new ApexPages.Message (ApexPages.Severity.ERROR, 'Select Some leads to convert'));
            return null; //terminate
           }
        //we don't want to create new account for each lead so create a new account,and give its id to each lead conversion
        if(accountName=='') //no account name given by user , give error
           {Apexpages.addMessage( new ApexPages.Message (ApexPages.Severity.ERROR, 'Please give Account name'));
            return null; //terminate            
           }
           
        Account leadAccount = new Account();
        leadAccount.name=accountName;
        Database.SaveResult result;
        try{
            result =Database.insert(leadAccount);   //create account,result will be used to retreive Id
        }
        catch (Exception e) {
            Apexpages.addMessage( new ApexPages.Message (ApexPages.Severity.ERROR, 'Error creating new account'));
            return null;//terminate
        }
        
        //LeadConvert[] array  to convert leads by api
        Database.LeadConvert[] leadsToConvert=new Database.LeadConvert[leadIdsToConvert.size()];
        //get status of converted lead from database itself,instead of hardcoading
        LeadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        //fill leadsToConvert array
        for(integer i=0;i<leadsToConvert.size();i++){
           leadsToConvert[i] = new Database.LeadConvert();
           leadsToConvert[i].setLeadId(leadIdsToConvert[i]); //required field
           leadsToConvert[i].setConvertedStatus(convertStatus.MasterLabel); //required field
           leadsToConvert[i].setAccountId(result.getId()); //setting to newly created account's Id
        }
        try{
            Database.LeadConvertResult[] lcr = Database.convertLead(leadsToConvert); //convert leads
        }
        catch (Exception e) {
            Apexpages.addMessage( new ApexPages.Message (ApexPages.Severity.ERROR, 'Error converting some leads'));
            return null;//terminate
        }
        
        //if all good then redirect to newly created account's detail page
        PageReference accountDetailsPage = new PageReference('/'+result.getId());
        //send redirect
        return accountDetailsPage.setRedirect(true);
       
    }
}