Sunday, January 3, 2016

How to Restrict creation of Contact on Lead Conversion

Here I'm trying to avoid the creation of Contact on Lead conversion.Here the thing is that we can't stop the contact creation on lead conversion because it's standard process .So to achieve this we have an alternative solution is to delete the contact after the lead got converted.

To Delete I have a written a trigger on Lead like below

 trigger noContactOnLeadConversion on Lead (after update)   
 {  
  list<contact> conlead=new list<contact>();  
  for(lead leadRec:Trigger.new)  
  {  
   if(trigger.oldMap.get(leadRec.id)isconverted==false && leadRec.isconverted && leadRec.ConvertedContactId != null)  
   {  
       contact con= new contact(Id=leadRec.ConvertedContactId);  
       conlead.add(con);  
   }  
  }  
  delete conlead;  
 }  





















When I start converting the lead I'm ending up with an error System.DmlException: Delete failed. First exception on row 0 with id 0039000001pvmhtAAA; first error: ENTITY_IS_DELETED, entity is deleted: [] .





















Then I added the logic to stop recursion trigger and tried with before trigger also but still I'm getting the same error with different screen but error is same







WorkAround for the Error 

Move the deletion of contact part to the @future method(i.e.,Asynchronous execution )and use Boolean variable to stop Recursion trigger.Below is the modified code snippet.

Trigger code:
 trigger noContactOnLeadConversion on Lead (after update)   
 {  
 if(!LeadUpdateHandler.stopleadUpdateTrigger)  
 {  
  LeadUpdateHandler.stopleadUpdateTrigger= true;  
  list<contact> conlead=new list<contact>();  
  for(lead leadRec:Trigger.new)  
  {  
   if(trigger.oldMap.get(leadRec.id).isconverted==false && leadRec.isconverted && leadRec.ConvertedContactId != null)  
   {  
    contact con= new contact(Id=leadRec.ConvertedContactId);  
    conlead.add(con);  
   }  
  }  
  LeadUpdateHandler.AsyncExecution(JSON.serialize(conlead));  
  }  
 }  

Handler Class Code:
 global class LeadUpdateHandler  
 {  
   public static boolean stopleadUpdateTrigger = false;  
   @future  
   public static void AsyncExecution(String JsonStr)  
   {  
    List<Contact> conList = new List<Contact>();  
     conList = (List<Contact>)JSON.deserialize(JsonStr, List<Contact>.class);  
     delete conList;  
   }  
 }  

For more update please join this site or just like my Facebook page I Love Coding..You? 

Enjoy.....!

No comments: