Showing posts with label Lead Conversion. Show all posts
Showing posts with label Lead Conversion. Show all posts

Wednesday, July 13, 2016

Native fields in Lead mapping for conversion

For Leads conversion process Salesforce provides out-of-box functionality for mapping Lead fields to Account/Contact/Opportunity.

Unfortunately there is a limitations - you can't map native Leads fields to target object's native field. For instance you can't map value from LeadSource ("native" Lead field) to AccountSource ("native" Account field).

Here is one of the possible ways to workaround the limitation. Solution could be modified based on particular business requirements. Please do not hesitate to contact us if you want to leverage this solutions in your Saleforce instance.

STEP 1: Create custom Formula(Text) field for Lead object
Name: LeadSourceCustom
Formula:  TEXT(LeadSource)

STEP 2: Create custom Text(100) field for Account object
Name: AccountSourceCustom

STEP 3: Amend Lead fields mapping to write value from LeadSourceCustom to AccountSourceCustom.

STEP 4: Create simple Trigger on Account object
/*
    Version        : 1.0
    Company        : Websolo inc. 
    Date           : 07/2016
    Description    : 
    Update History : 
*/
trigger AccountSourceTrigger on Account (before update,before insert) {
    for(Account a: Trigger.new){
        if(a.AccountSourceCustom__c != null && a.AccountSourceCustom__c != '' && (a.AccountSource == null || a.AccountSource == '')){
            a.AccountSource = a.AccountSourceCustom__c;
        } 
    }
}

As a result this trigger will update native AccountSource field with value from "native" LeadSource field.

EXTRA NOTE:
We can't use WorkFlow as a workaround because AccountSource field is picklist and when we create workflow action to update this field we can write only specific value from the picklist.

Thursday, August 7, 2014

Salesforce Lead Conversion - How To Specify resulted Account/Contact/Opportunity Record Types

As known when user converts a Lead, Salesforce creates new Account, Contact and Opportunity using the information from the Lead.

There is uncomfortable feature that Salesforce users struggle for a long time: "the default record type of the user converting the Lead is assigned to records created during lead conversion".

I.e. User (who's Profile has access to multiple Record Types) can not control with which Record Type Account, Contact and Optionally will be created. It always will be "Default Record Type" selected by Administrator for the User's profile. As a result Users will have to manually change Record Types for newly created records. Which is uncomfortable and takes valuable time.

There are two workarounds to enhance user experience and overcome the issue. Please find below workarounds description with analysis about their PROS and CONS.

Note: Updated 2015/02/05 with corrections related to solution #1

#1 Use Workflow Rules to update Record Type of created Account, Contact and Opportunity 

Easy to implement solution which not requires advanced Salesfroce Development skills.

Step 1: Create three picklist fields on Lead object (Expected Account Type, Expected Contact Type, Expected Opportunity Type) and populate them with Record Types names you have for Accounts, Contacts and Opportunities objects. These field will be visible to Users to let them to select Record Type they want for created after Lead Conversion records.

Step 2: Create three text fields with the same names on Accounts (Expected Account Type), Contacts (Expected Contact Type) and Opportunity (Expected Opportunity Type). These fields could be invisible for Users an will be used by workflow rules.

Step 3: Map new Leads fields to related fields on Accounts, Contacts and Opportunities objects.

Step 4:  You will have to create as many Workflow Rules and Actions for Accounts, Contacts and Opportunities as many Record Types you have in these objects. For instance if you have two Record Types for Account you will have to create two Workflows dedicated for each of them.

Set every Workflow Rule with Evaluation Criteria "Evaluate the rule when a record is created" and Rule Criteria  (for example) "Account: Expected Account Type EQUALS [YOUR RECORD TYPE NAME]. Add Action as field update to update the Record Type field to value you want to change in this particular Workflow. Repeat the same for every Account Record Type. Then do the same for Contacts and Opportunities Record Types.

Step 5: Activate Workflows and test the solution.

PROS: Pretty easy to implement. Does not require APEX coding and triggers development.
CONS: Six custom fields in four objects. Multiple (depend on your SFDC solution -  could be quite many) Workflow Rules/Actions to monitor and update if any changes required.

#2 Use APEX trigger Rules to update Record Type of created Account, Contact and Opportunity 

A little more complicated from development point of view but more efficient and easy to support solution.

Instead of the workflows this solution use a single APEX trigger with Helper class to handle all needed functionality.

Step 1: The same as above. Create three picklist fields on Lead object (Expected Account Type, Expected Contact Type, Expected Opportunity Type) and populate them with Record Types names you have for Accounts, Contacts and Opportunities objects. These field will be visible to Users to let them to select Record Type they want for created after Lead Conversion records.

Step 2: Create trigger and helper class. See code samples below.

Step 3: Test and deploy the solution to Production environment.

PROS: Easy to implement and support.
CONS: None

APEX Trigger: LeadConversionExpectedRecordTypes
/*
Version        : 1.0
Company        : Websolo inc. 
Date           : 08/2014
Description    : 
Update History :
*/
trigger LeadConversionExpectedRecordTypes on Opportunity (after insert) 
{
    Boolean uiCR = false;
     if(Test.isRunningTest())
     {
       uiCR  = true;
     }
     else
     {
      if(Trigger.new.size() == 1)
      {
       uiCR  = true;
      }
     }
     if(uiCR  == true)
     {
          for(Opportunity opp: Trigger.new)
          {
             LeadConversionExpectedRecordTypesHelper.UpdOpp(opp.id);
          }
     }
}

APEX helper class: LeadConversionExpectedRecordTypesHelper
/*
    Version        : 1.0
    Company        : Websolo inc. 
    Date           : 08/2014
    Description    : help class for LeadConversionExpectedRecordTypes trigger 
    Update History :
*/
public class LeadConversionExpectedRecordTypesHelper
{
 @future(callout = true)
 public static void UpdOpp(id oppObjID)
 {
   map mapRC = new map();
   for(RecordType a: [select Name, id from RecordType where SobjectType = 'Opportunity'])
   {
     mapRC.put(a.Name, a.id);
   }
   
   map mapRCacc = new map();
   for(RecordType a: [select Name, id from RecordType where SobjectType = 'Account'])
   {
     mapRCacc.put(a.Name, a.id);
   }   
   
   Opportunity opp = [select id, OwnerId, RecordTypeId from Opportunity where id =: oppObjID];   
   List listLead = new List();
   if(!test.isRunningTest())
   {
       listLead = [select id, Expected_Opportunity_Type__c, Expected_Account_Type__c, ConvertedAccountId  from Lead where ConvertedOpportunityId =: opp.id AND isConverted = true];
   }
   else
   {
       listLead = [select id, Expected_Opportunity_Type__c, Expected_Account_Type__c, ConvertedAccountId from Lead];        
   }   
   if(listLead.size() > 0)
   {
    if(listLead[0].Expected_Opportunity_Type__c != null)
    {
      opp.RecordTypeId = mapRC.get(listLead[0].Expected_Opportunity_Type__c);
      update opp;
    }
    if(listLead[0].ConvertedAccountId != null)
    {
      Account acc = [select id, RecordTypeId from Account where id=:listLead[0].ConvertedAccountId];
      if(listLead[0].Expected_Account_Type__c != null)
      {
        acc.RecordTypeId = mapRCacc.get(listLead[0].Expected_Account_Type__c);
        update acc;
      }
    }
   }
 }
}

Monday, July 14, 2014

Custom Validation For Lead Conversion

To increase data quality Sales Managers encourage their Sales Representatives to gather as much as possible information about Leads before Conversion it to Contact, Account and Opportunity.

There are multiple techniques to enforce SFDC Users to enter values to all required fields before the Conversion. Let's discuss these techniques with implementation details and all its PROS and CONS.

How to enforce Sales Reps to enter values to required Lead fields before the Conversion.


#1 Make fields required on Lead layout

The most obvious and straight forward solution. But not the best one. Salesforce Lead layout allows Administrator to make some fields required (mandatory). But it's hard for Sales representative to get values for all required fields at once. In most cases Sales person can enter some data initially and then revisit the Lead record to update the rest of the important fields later.

PROS: Easy to implement
CONS: Not convenient for Users. To make any update (edit the Lead) User have to enter values in all required fields at once.

#2 Use a validation rule to fire when Lead is actually converted

Such validation rule will help to make certain fields required before converting the Lead but not require them to be entered when User edits the Lead's record.

Here is example of Validation Rule (could be adjusted to meet particular business requirements)

Rule Name:  Lead_Conversion_Validation

Error Condition Formula:
AND(IsConverted,
OR(
ISBLANK(Email),
ISBLANK(Phone),
ISBLANK(Website),
ISBLANK(TEXT(LeadSource)),
ISBLANK(TEXT(Range_of_Revenues__c)),
ISBLANK(State),
ISBLANK(Street),
ISBLANK(City),
ISBLANK(PostalCode),
ISBLANK(Country)
))

Error Message:
Please fill out following fields before conversion:
- Email
- Phone
- Full Address
- Website
- Range of Revenues
- Lead Source

PROS: Pretty easy to implement
CONS: Still not convenient for Users. The Validation Rule fires ONLY when user hit the Convert button on the Lead page, entered data on Conversion page and clicked Convert button. If something goes wrong (any required field is missed) - user will lose his time and will have to return back to the Lead page to enter missed data. Also Error Message is very general and does not really help the User to identify the missed field(s).

#3 Use workflow to update the Lead's Record Type/Layout when User enters all required for conversion fields

To build this solution you will have to create and support two Lead Record Types and related identical Lead layouts:
 - NotReadyForConversion (default) Lead Record Type and related Lead layout without Convert button
 - ReadyForConversion Record Type and related Lead layout with Convert button

Custom workflow have to check/monitor if all required fields have data.
When the necessary fields are filled out workflow action will update the Lead's Record Type to ReadyForConversion and Users will see the Lead in new layout - with Convert button.

PROS: Allows user to edit the Lead and Convert it only when all required fields are filled out.
CONS: Required two Record Type and two Layouts. Difficult to maintain - especially if you have multiple Leads Record Types/Layouts/User Profiles. Still not convenient for Users. No Error message. User can't see/check out which fields are still missing.

#4 Override the standard 'Convert' button with custom button and related VF page/Controller

SFDC Administrator/Developer can create a new custom 'Convert' button to be used on Lead layout instead of native one. Click to the button will call popup window with custom VF page and Controller to check if all required fields have data (based on particular business requirements).
  • If all required fields are filled out - embedded in VF page JavaScript will auto close the pop up window and redirect User to Conversion page.
  • If any required field(s) not filled out yet - VF page will show User Error message with information about which field(s) have to be entered. By click to Close button / or lose pop up window focus / or in 10 seconds of inactivity - close/auto close pop up window. User still on the Lead page and can enter data in missed field.
PROS: Allows user to edit the Lead and Convert it only when all required fields are filled out. User can easy check out which fields are missing to let them to convert the Lead.
CONS: Required some Force.com development. But final result worth the efforts - Sales Users are happy with the solution which help then save time and meet data quality criteria.

Solution Code Sample: (please contact us if you have questions or want to modify this solution to meet your particular business requirements)

Custom Button

Label: Convert
Object Name: Lead
Name: ConvertCustom
Behavior: Execute JavaScript
Display Type: Detail Page Button
OnClick JavaScript

var url = "/apex/Lead_Conversion_Validation?id={!Lead.Id}";
var width = "350";
var height = "350";
window.open(url, '','scrollbars=no,resizable=no,status=no,toolbar=no,menubar=no, width=' + width + ',height=' + height + ',left=' + ((window.innerWidth - width)/2) + ',top=' + ((window.innerHeight - height)/2) );

Visualforce Page: Lead_Conversion_Validation
<!--
Version        : 1.0
Company        : Websolo Inc. (websolo.ca)
Date           : 07/2014
Update History :
-->
<apex:page standardController="Lead" showHeader="false" sidebar="false" extensions="LeadConversionValidation">
<style>
h2
{
  width: 300% !important;
}
</style>
   <script>
window.onload = function(){
window.onblur = function(){window.close();}
     if(document.getElementById('sd').innerHTML == "")
     {
      var ids = document.getElementById('ids').innerHTML;
      window.opener.location.href="/lead/leadconvert.jsp?retURL=%2F" + ids + "&id=" + ids;
      window.top.close();
     }
     else
     {
         setTimeout(function(){
          window.close();
        }, 10000);   
     }
};
   </script>
      <div id="sd" style="display: none;">{!reft}</div>
      <div id="ids" style="display: none;">{!leadobjid}</div> 
 <apex:pageBlock title="Lead Conversion Validation">
      <apex:pageBlockButtons location="bottom">
       <button onclick="window.close();">Close</button>
     </apex:pageBlockButtons>
      <apex:pageMessage severity="error" strength="1">
          <apex:outputText value="{!error}" escape="false" />
          <apex:outputText value="{!sterrmsg}" escape="false" rendered="{!sterr}"/><br />         
      </apex:pageMessage>
  </apex:pageBlock>
</apex:page>


Apex Class: LeadConversionValidation
(controller - code could be adjusted to meet particular business requirements)
/*
Version        : 1.0
Company        : Websolo Inc. (websolo.ca)
Date           : 07/2014
Update History :
*/
public class LeadConversionValidation
{
    public id leadobjid {get; set;}
    public String error {get; set;}
    public String reft {get; set;}
    public Boolean sterr {get; set;}
    public String sterrmsg {get; set;}
    public LeadConversionValidation(ApexPages.StandardController controller)
    {
      sterr = false;
      sterrmsg = 'To convert Lead please change Lead Status to Contacted';
      error = 'Please fill out following fields before conversion:<br />';
      reft = '';
      leadobjid = ((Lead) controller.getRecord()).id;
      Lead leadobj = [select Status, LastName, Keywords__c, Financing_Notes__c, Email,Phone,Website,Employees__c,Rapport__c,LeadSource,Range_of_Revenues__c,State,Street,City,PostalCode,Country from Lead where id =: leadobjid ];
      if(leadobj.LastName == null ||
        leadobj.Keywords__c  == null ||
        leadobj.Financing_Notes__c == null ||
        leadobj.Email == null ||
        leadobj.Phone == null ||
        leadobj.Website == null ||
        leadobj.Employees__c == null ||
        leadobj.Rapport__c == null ||
        leadobj.LeadSource == null ||
        leadobj.Range_of_Revenues__c == null ||
        leadobj.State == null ||
        leadobj.Street == null ||
        leadobj.City == null ||
        leadobj.PostalCode == null ||
        leadobj.Country == null)
        { 
          reft = '1';
          if(leadobj.Keywords__c  == null){error = error + '- Keywords<br />';}
          if(leadobj.Financing_Notes__c  == null){error = error + '- Call Notes (at least 100 characters)<br />';}
          if(leadobj.Email == null){error = error + '- Email<br />';}
          if(leadobj.Phone == null){error = error + '- Phone<br />';}
          if(leadobj.Website == null){error = error + '- Website<br />';}
          if(leadobj.Employees__c  == null){error = error + '- Employees Range<br />';}
          if(leadobj.Rapport__c == null){error = error + '- Rapport<br />';}
          if(leadobj.LeadSource == null){error = error + '- Lead Source<br />';}
          if(leadobj.LastName == null){error = error + '- Lead Name<br />';}
          if(leadobj.Range_of_Revenues__c == null){error = error + '- Range of Revenues<br />';}
          if(leadobj.State == null || leadobj.Street == null || leadobj.City == null || leadobj.PostalCode == null || leadobj.Country == null){error = error + '- Full Address<br />';}     
        }
        if(leadobj.Status != 'Contacted')
        {
          //sterr = true;
          if(reft == '1')
          {
           sterr = true;
          }
          else
          {
           error = '';
           reft = '1';
           sterr = true;
          }
        }         
    }
}


Apex Class: TestLeadConversionValidation (test coverage)
Version        : 1.0
Company        : Websolo Inc. (websolo.ca)
Date           : 07/2014
Update History :
*/
@isTest
private class TestLeadConversionValidation
{
static testMethod void myUnitTest() 
{
Lead ld = new Lead();
ld.LastName = 'test';
ld.Company = 'test';
ld.Email = 'test@test.com';
ld.Phone = '1112223456';
insert ld;
LeadConversionValidation obj = new LeadConversionValidation(new ApexPages.StandardController(ld));
}
}