Access Lead conversion field mappings from Apex?

I’ve written some Apex code to override the lead conversion process. if the contact exists, the client wants to update all the contact fields with the lead field data when the lead field is not null.

There are over 40 field mappings. Is there a way to access the field mappings table so I don’t have to hardcode the field names?

Answer

Now it is possible to retrieve Lead Conversion fields through Apex with help of Metadata API. To use this code you need to have MetadataService class from https://github.com/financialforcedev/apex-mdapi/blob/master/apex-mdapi/src/classes/MetadataService.cls

MetadataService.MetadataPort service = new MetadataService.MetadataPort();
service.SessionHeader = new MetadataService.SessionHeader_element();
service.SessionHeader.sessionId = UserInfo.getSessionId();
service.CallOptions = new MetadataService.CallOptions_element();
service.timeout_x = 120000;

List<MetadataService.LeadConvertSettings> leadConvertSettings = (List<MetadataService.LeadConvertSettings>) service.readMetadata('LeadConvertSettings', new List<String>{'LeadConvertSettings'}).getRecords();

for (MetadataService.LeadConvertSettings leadConvertSetting : leadConvertSettings) {
    for (MetadataService.ObjectMapping objectMapping : leadConvertSetting.objectMapping) {
        System.debug(objectMapping.inputObject + ' -> ' + objectMapping.outputObject);
        for (MetadataService.ObjectMappingField fieldMapping : objectMapping.mappingFields) {
            System.debug('\t' + fieldMapping.inputField + ' -> ' + fieldMapping.outputField);
        }
    }
}

Attribution
Source : Link , Question Author : David Cheng , Answer Author : Mariia Illarionova

Leave a Comment