function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
SushupsiSushupsi 

Coding Tips for Custom Lead "Convert" Functionality.

:smileysad::smileysad:

 

Hi All,

 

I have a requirement to make few Fields mandatory in the intermediatory Convert Layout of the Lead tab. I was searching for a solution as to how to modify the code for "Convert" functionality. Please help me on this by providing any code snippets as to how to begin the coding.

 

My Queries are:

 

1.) Can a Trigger be written on the Convert button and be addressed as  "Before convert" some thing like that.

 

2.) Please throw light on how to design a custom button , which on click performs the exact functionality as Convert Lead.

 

3.) Please provide information about "ConvertLead" function. I happened to see this kind of discussion on the boards, Hope i am right with that.. Please provide me with a snippet as to how to customise that functionality.

 

4.) How do i append any custom field information filled while conversion (a mandatory field while converting) to the opportunity name,like  "Opportunity name : opportunity-myfield name".

 

Please help me with this , help is urgently needed.

TIA.

 

Sushupsi.

Best Answer chosen by Admin (Salesforce Developers) 
SushupsiSushupsi

Hi All,

 

I am able to solve the problem. Please find the solution below :d

 

My Page Looks Like this :

 

<apex:page standardController="lead" cache="true" action="{!autorun}" extensions="leadController" >
<br/><br/>
<apex:messages style="color:red; font-weight:bold; text-align:center;"/>
<apex:form >
<center>
<apex:commandLink value="Redirect to Lead" style="color:blue; font-weight:bold;" action="{!RedirecttoLead}"/>
</center>
</apex:form>
</apex:page>

 

The Controller is as Below :

 

public class leadController
{
    Public lead lObj;
    Public Id leadId;
    public leadController(ApexPages.StandardController stdController)
    {
        leadId = ApexPages.currentPage().getParameters().get('id');
        lObj = (leadid == null) ? new Lead():[SELECT Money_Order__c, Money_Transfer__c from lead where id =: leadid];
    }
    public PageReference autoRun()
    {
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(leadId);
        LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        if(lObj.Money_Order__c == true || lObj.Money_Transfer__c == true){
        Database.LeadConvertResult lcr = Database.convertLead(lc);
        System.assert(lcr.isSuccess());
        Id oppId = lcr.getOpportunityId();
        PageReference Page = new PageReference('https://cs3.salesforce.com/'+oppId);
        Page.setRedirect(true);
        return Page;
        }
        else{
        lObj.addError('Lead cannot be converted without Product Selection !');
        lObj.addError('Please Select Atleast One Product');
        }
        return null;
    }
    Public PageReference RedirecttoLead(){
        PageReference Page = new PageReference('https://cs3.salesforce.com/'+leadId);
        Page.setRedirect(true);
        return Page;
    }
}

 

 

Using this i was able to createa custom button and convert the Lead.

Posting this solution since it can be a help to others.

 

Bye

- Sushupsi

All Answers

Ispita_NavatarIspita_Navatar

Please find answer to the various query posted by you around the custom Lead Conversion Functionality:-

1.Can a Trigger be written on the Convert button and be addressed as  "Before convert" some thing like that. - Instead of a trigger which fires on the DML manipulations like Add/ Edit/ Delete/ Update you need to code something which fires on getting input from user via UI . So the best option would be to code a custom Visual Force page couple with Apex Classes.

 

2. You can achieve this via "Custom Button" and either execute a snippet which calls functions written in Apex class or redirects user to a Visual Force oage which provides a summary/preview of object creation to the user (like Account/ Opportunity/ Activity / Contact ) and providing a button to the user to confirm the changes or information thus shown in the intermediate page.

 

3. As of information about Convert lead you may be aware it is accompanied by the creation of :-

  a. Account

  b. Opportunity

  c. Contact

  d. Activity

 

4. Your custom code will easily enable you to assign the mandatory fields  and in case the required information is lacking you can raise error.

 

Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.

SushupsiSushupsi

Hi Navatar,

 

Firstly, Thank you for your response. I appreciate your help.

 

I have sarted off with the method that you have suggested. I have reached to the same conclusion though. :smileywink:

 

Please allow me to explain what i have done as my approach.

 

My requirement now has changed , we do not need the intermediatory convert page, but just create the account lead and contact. I have gone through the forums (apex dev), and written the following code.

 

Please Help me understand the actual way in which the function is to be called is right or any modification is required.

 

This is my VF page that opens on click of a custom detailed page button for convert :

 

<apex:page standardController="lead" cache="true" extensions="leadController" action="{!autoRun}">

</apex:page>

 

 

My Controller Looks like this :

public class leadController
{
    public leadController(ApexPages.StandardController stdController)
    {
    
    }
    public PageReference autoRun()
    {
        
        PageReference Page = new PageReference('https://cs3.salesforce.com/006/o');
        Page.setRedirect(true);
        return Page;
    }
    public static void ConvertLead(lead[] leads)
    {
        Database.LeadConvert[] leadsToConvert = new Database.LeadConvert[0];
        Database.LeadConvert converter = new Database.LeadConvert();
        for (lead l : leads){
        converter.setLeadId(l.id);
        account account = new account(name='test');
        insert account;
        converter.setAccountId(account.id);
        contact contact = new contact(firstname='test', lastname='test',accountid=account.id);
        insert contact;
        converter.setContactId(contact.id);
        //converter.setOwnerId('00570000000oflK');
        converter.setConvertedStatus('Qualified - Converted');
        converter.setDoNotCreateOpportunity(false);
        leadsToConvert.add(converter);
        }
        Database.ConvertLead( leadsToConvert, true );
    }
}

 I unerstand that i have not written the convert lead on page load.(Like the autorun)

 

My queries are as follows:

 

1.) As per my understaning the Static method has its existence even before the class obj is created so is the static method 'ConvertLead' already allocated with space and is running(since no explicit call).

 

2.) I need the account , opportunity names from my lead fields only.

     account account = new account(name='test');

 

But the above statement is feeding the account name statically. I have previously used the following trigger to feed lead name to opportunity.

            Opportunity opp = [Select o.Id, o.Name, o.Description from Opportunity o Where o.Id = :Trigger.new[0].ConvertedOpportunityId];
            opp.Name = opp.Name+Productname;
            update opp;

 Can some thing similar be done in apex code.

 

Please respond to my post. I need to complete the lead Conversion ASAP, but unfortunately not understanding how to proceed. Can you specify me the steps of declaring the leadconvert object and handling the account , contact, opportunity creation explicitly and also can mapping of fields (custom) be done through the above code logic.

 

:smileysad:

 

TIA

- Sushupsi.

 

SushupsiSushupsi

Hi All,

 

I am able to solve the problem. Please find the solution below :d

 

My Page Looks Like this :

 

<apex:page standardController="lead" cache="true" action="{!autorun}" extensions="leadController" >
<br/><br/>
<apex:messages style="color:red; font-weight:bold; text-align:center;"/>
<apex:form >
<center>
<apex:commandLink value="Redirect to Lead" style="color:blue; font-weight:bold;" action="{!RedirecttoLead}"/>
</center>
</apex:form>
</apex:page>

 

The Controller is as Below :

 

public class leadController
{
    Public lead lObj;
    Public Id leadId;
    public leadController(ApexPages.StandardController stdController)
    {
        leadId = ApexPages.currentPage().getParameters().get('id');
        lObj = (leadid == null) ? new Lead():[SELECT Money_Order__c, Money_Transfer__c from lead where id =: leadid];
    }
    public PageReference autoRun()
    {
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(leadId);
        LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        if(lObj.Money_Order__c == true || lObj.Money_Transfer__c == true){
        Database.LeadConvertResult lcr = Database.convertLead(lc);
        System.assert(lcr.isSuccess());
        Id oppId = lcr.getOpportunityId();
        PageReference Page = new PageReference('https://cs3.salesforce.com/'+oppId);
        Page.setRedirect(true);
        return Page;
        }
        else{
        lObj.addError('Lead cannot be converted without Product Selection !');
        lObj.addError('Please Select Atleast One Product');
        }
        return null;
    }
    Public PageReference RedirecttoLead(){
        PageReference Page = new PageReference('https://cs3.salesforce.com/'+leadId);
        Page.setRedirect(true);
        return Page;
    }
}

 

 

Using this i was able to createa custom button and convert the Lead.

Posting this solution since it can be a help to others.

 

Bye

- Sushupsi

This was selected as the best answer
Money.ax731Money.ax731

My code has 69% coverage need help for deployment
My code has 69% coverage. I need at least 75%. I am stuck at the very last step. Please help asap since I need to deploy this code.

Any help would be wonderful.

Based on the lead type i am trying to populate the Channel Partner Account or the End Customer Account which needs to be copied from the account name field of opportunity on Lead Convert.

I have the apex class below till where it converts the lead but I am trying to query the converted opportunity.


Both Trigger and Apex Class are pasted below.

Almost there at 69% coverage

trigger LeadConvertAccountNameType on Lead (before update) {
system.debug('trigger size is: ' + trigger.size);
system.debug('converted opp id is: ' + trigger.new[0].ConvertedOpportunityId);
system.debug('lead RT id is: ' + trigger.new[0].RecordTypeID);
if( trigger.isUpdate && trigger.new.size() == 1 && trigger.new[0].ConvertedOpportunityId != NULL) {

      if (trigger.new[0].IsConverted && trigger.new[0].RecordTypeID == '01280000000Ln1Y') {          
       // Assign the value from the Account Name "Status" field to the Channel Partner Name "Type" field  
                Opportunity opp = [SELECT Id, AccountId FROM Opportunity WHERE Opportunity.Id = :trigger.new[0].ConvertedOpportunityId];
                opp.Channel_Partner_Account__c = opp.AccountId;
                system.debug('assigning channel partner');   
                update opp;       
       } else if (trigger.new[0].IsConverted && trigger.new[0].RecordTypeID == '01280000000Ln1d') {
                Opportunity opp = [SELECT Id, AccountId FROM Opportunity WHERE Opportunity.Id = :trigger.new[0].ConvertedOpportunityId];
                opp.End_Customer_Account__c = opp.AccountId;
                system.debug('assigning end user account');
                update opp;
       }
    }
}


Class

public class TestLeadConvertAccountNameType{
       
        static testMethod void test() {
       
                   
                   
              
            Lead l = new Lead();
            l.LastName = 'CRM Testing INC';
            l.Company = 'CRM Testing INCtest';
            l.city = 'test';
            l.street = 'test';
            l.state = 'CA';
            l.country = 'United States';
            l.status = 'Qualified Lead';
            l.sub_status__c = 'Bad Phone';
            l.RecordTypeId = '01280000000Ln1Y';
            l.OwnerId = '00580000003TJmH';
            l.Product_interest__c = 'NAS';
            l.Lead_Type__c = 'Distribution';
            l.email = 'test@testnetgear.com';
            insert l;
           
         
   
   
   
   
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(l.id);
        LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where IsConverted=true limit 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        if(l.Lead_Type__c == 'Distribution' || l.Lead_Type__c == 'End User'){
        Database.LeadConvertResult lcr = Database.convertLead(lc);
        System.assert(lcr.isSuccess());
        Id oppId1 = lcr.getOpportunityId();
        system.debug('opp id is: ' + oppId1);
        system.debug('opp id is: ' + lcr.getopportunityId());
       
       
           I need something here to make the coverage go to 75%. How do I validate the opportunity is where i am stuck!!
          
        }
        else{
        l.addError('Lead cannot be converted without Product Selection !');
        l.addError('Please Select Atleast One Product');
        }
       
    }
   
         

                    
}

goabhigogoabhigo

Thanks. It works fine. I had to modify the class according to my need.

Similar to this can you please give idea about writing trigger for the same(converting lead).

SudeepSudeep

Hi,

 

 

 I am working for the same issue

Leads Object is “Converted” to an account and opportunity I need the following fields also moved to the Account Object.

 

Fields:  Lead Source, Lead Source Date, Lead Source Sub,  Referrer.



 

Please Help me

 

 

Pradeep

SushupsiSushupsi

Hi Sudeep,

 

Nice to hear from you. I have a small query about how are you going about it.

These seems to be standard fields, i will get back to you on this in a while.

 

For the case of any custom field mappings, we do have a standard feature "Map Lead Fields" in the custom fields section of the Lead object.

 

Will get back with some help to you.

 

Regards,

Sushupsi

PrasadVRPrasadVR

 Hello Sushupsi, 

      How to use setaccountid and set contactid values while converting the leads becase i want to customize the lead conversion process same as standard 

aghattamanen@yahoo.comaghattamanen@yahoo.com

Hi all,

I have the same requirement for my customer and did the second method as mentioned in the post through intermediate page to be confirmed by the user to create the records in Account,Contact and opportunities on the same visualforce page.

We did it using the extension controller and custom settings.Now the problem is once the user click on convert lead custom button then the page is being redirected to the visualforce page in edit mode where we will have three sections for account,contacts and opportunities.When this page is displayed in edit mode,we need to take some of the field's data from lead and display it by default on the fields with in the visualforce page.so that the user can verify the details and then fill the missing information if needed then the user can save this.

 

So please suggest is there any way to pass this information from lead to visualforce page and display the field values on edit mode of vf page?

 

Thank you so much for your support.

aghattamanen@yahoo.comaghattamanen@yahoo.com

Hi ,

I have the same requirement for my customer and did the second method as mentioned in the post through intermediate page to be confirmed by the user to create the records in Account,Contact and opportunities on the same visualforce page.

We did it using the extension controller and custom settings.Now the problem is once the user click on convert lead custom button then the page is being redirected to the visualforce page in edit mode where we will have three sections for account,contacts and opportunities.When this page is displayed in edit mode,we need to take some of the field's data from lead and display it by default on the fields with in the visualforce page.so that the user can verify the details and then fill the missing information if needed then the user can save this.

 

So please suggest is there any way to pass this information from lead to visualforce page and display the field values on edit mode of vf page?

 

Thank you so much for your support.

PrasadVRPrasadVR

Yes , you can do this ,

 

  what all you need to do is 

 1.Pass the current Lead Id to the URL when user clicks on convert button 

2. Now you have the lead Id in URL take that and with the help of that Id make a query on lead and take the necessary information in your controller  

3. Now you can display same in vf page