Thursday 6 November 2014

Dynamic field mapping using Custom Settings



Some time we need to pass one object information to another object. So in this regards developer needs to write a trigger / apex code and needs to define each column mapping in the code. But it may be possible that in future field mapping will change or some new fields will introduce. For that we again need to change code.

In that case we need to create a dynamic field mapping between two object. That functionality  we can achieve with custom setting.
 In my last project i have done some code for same functionality  

Requirement :-

As per client requirement he want to store the Lead information in Pre - Lead and then he want to convert the pre- lead into Lead after some validation. 

Solution :

So for above requirement we have created a object Pre-lead and on same object we have created a button convert lead. while converting the pre- lead into lead we need to provide dynamic field mapping between two object. For that i have created the custom setting "MyLeadToLeadMapping__c" with one custom field "Lead_Field_API_Name__c"



After that i have added the field mapping in custom setting



Code :---

public with sharing class ConvertMyLead
{
public Boolean showmessage{get;set;}
public string MyLeadid{get;set;}
public Lead LeadObj;
string qry = '';
    Map<string, string> MapMappingTable=new map<string,string>();

    public Pagereference MapLeadfields()
    {
        Pagereference pageref;
        Savepoint sp = Database.setSavepoint();
        try
        {
LeadObj=new Lead();
MyLeadid=ApexPages.currentPage().getParameters().get('MyLeadid');
getAllMapping();
qry = 'select ' + qry + 'id FROM My_Lead__c where id =: MyLeadid';
My_Lead__c MyLead = Database.query(qry);

for(String sMyLeadField: MapMappingTable.keySet())
{
String sLeadField = MapMappingTable.get(sMyLeadField);
LeadObj.put(sLeadField, MyLead.get(sMyLeadField));
}

LeadObj.OwnerID = UserInfo.getUserId() ;
LeadObj.status='new';
insert LeadObj;
showmessage=true;
pageref=new Pagereference('/'+LeadObj.Id);
return pageref;
        }
        catch(Exception ex)
        {
            Database.rollback(sp);
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage());
            Apexpages.addMessage(msg);
            return null;
       }
    }
 
    public Map<string,string> getAllMapping()
    {
        qry ='';
        try{
             for (MyLeadToLeadMapping__c mappingTableRec : MyLeadToLeadMapping__c.getall().Values())
             {
                if (mappingTableRec.Name != null && mappingTableRec.Lead_Field_API_Name__c != Null )
                {
                    MapMappingTable.put(mappingTableRec.Name , mappingTableRec.Lead_Field_API_Name__c);
                    qry += mappingTableRec.Name + ',';
                }
             }
        }
        catch(exception ex)
        {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage());
            Apexpages.addMessage(msg);
        }
        return MapMappingTable;
    }
 
    public PageReference goBack()
    {
      PageReference pf = new PageReference('/'+MyLeadid);
      return pf;
    }

    public boolean getHasErrors()
    {
        return ApexPages.hasMessages(ApexPages.severity.ERROR);
    }
}


Thanks,
Amit Chaudhary 


2 comments:

  1. Hi, i'm new to SF and learning. Have been a follower of your nice blog.
    I tried to execute this example after mimicking all steps.
    I was able to SOQL custom settings from Dev Console.

    On clicking a "Detail page button" from My Leads page:

    {!REQUIRESCRIPT("/soap/ajax/14.0/connection.js")}
    {!REQUIRESCRIPT("/soap/ajax/14.0/apex.js")}
    var result = sforce.apex.execute("ConvertMyLead", "MapLeadfields",{});
    alert(result);
    window.location.reload();

    im receiving this alert

    A problem with the OnClick JavaScript for this button or link was encountered:{faultcode:'soapenv:Client', faultstring:'No operation available for request {http://soap.sforce.com/schemas/package/ConvertMyLead}MapLeadfields, please check the WSDL for the service.', }

    and im stuck and searching the endless internet.

    Would appreciate your feedback..

    Thanks for your time

    ReplyDelete
  2. Hi amit I am new to salesforce I am trying to implement your code i am getting some errors, and one more thing should we have to write the visualforce page for this apex code and would please provide me that it will helpful to me and the code i have wrote is
    .
    .
    public with sharing class ConvertMyLead {
    public Boolean showmessage{get;set;}
    public string MyLeadid{get;set;}
    public Lead LeadObj;
    //public string qry{get;set;}
    string qry = '';
    Map MapMappingTable=new Map();
    public Pagereference MapLeadfields()
    {
    Pagereference ref;
    savepoint sp=Database.setSavepoint();
    try
    {
    LeadObj=new Lead();
    MyLeadid=ApexPages.currentPage().getParameters().get('MyLeadid');
    getAllMapping();
    qry = 'select ' + qry + 'id FROM My_Lead__c where id =: MyLeadid';
    My_Lead__c MyLead = Database.query(qry);

    for(String sMyLeadField: MapMappingTable.keySet())
    {
    String sLeadField = MapMappingTable.get(sMyLeadField);
    LeadObj.put(sLeadField, MyLead.get(sMyLeadField));
    }

    LeadObj.OwnerID = UserInfo.getUserId() ;
    LeadObj.status='new';
    insert LeadObj;
    showmessage=true;
    ref=new Pagereference('/'+LeadObj.Id);
    return ref;
    }
    catch(Exception ex)
    {
    Database.rollback(sp);
    ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage());
    Apexpages.addMessage(msg);
    return null;
    }
    }
    public Map getAllMapping()
    {
    qry ='';
    try{
    for (MyLeadToLeadMapping__c mappingTableRec : MyLeadToLeadMapping__c.getall().Values())
    {
    if (mappingTableRec.Name != null && mappingTableRec.Lead_Field_API_Name__c != Null )
    {
    MapMappingTable.put(mappingTableRec.Name , mappingTableRec.Lead_Field_API_Name__c);
    qry += mappingTableRec.Name + ',';
    }
    }
    }
    catch(exception ex)
    {
    ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, ex.getMessage());
    Apexpages.addMessage(msg);
    }
    return MapMappingTable;
    }
    public PageReference goBack()
    {
    PageReference pf = new PageReference('/'+MyLeadid);
    return pf;
    }

    public boolean getHasErrors()
    {
    return ApexPages.hasMessages(ApexPages.severity.ERROR);
    }
    }.
    .
    .
    .
    The errors are
    18th line Invalid type: My_Lead__c
    23rd line Variable does not exist: MyLead

    please anyone help me to overcome this



    Thank you in advance
    Kavya

    ReplyDelete