I have objA and objB . objA has around 350 fields and some fields in objA starts as SVCM__xyz__c but those fields in objB starts as xyz__c . Now i want objB to be mirrior of objA. I need to write a trigger to objA to perform this task. Need to create mapping between them. fields in objB are subset of objA.
I am trying to avoid hardcoding field names into the trigger. I did fetch all the fields and removed SCVM__ from the each field in ObjA. Now how to create mapping between fields. Code I have so far is below.
public with sharing class CloneRecordToWorkOrderHandler {
Map<String,Schema.SObjectField> mapFieldMapManaged;
static Map<String,String> mapLabelToFieldSV;
Map<String,Schema.SObjectField> mapFieldMapNew;
static Map<String,String> mapLabelToFieldWO;
public CloneRecordToWorkOrderHandler() {
mapFieldMapManaged = Schema.getGlobalDescribe().get('SVMXC__Service_Order__c').getDescribe().Fields.getMap();
mapFieldMapNew = Schema.getGlobalDescribe().get('Work_Order__c').getDescribe().Fields.getMap();
String key = ' ';
String value = ' ';
mapLabelToFieldSV = new Map<String,String>();
mapLabelToFieldWO = new Map<String,String>();
for(String s:mapFieldMapManaged.keySet()) {
key = mapFieldMapManaged.get(s).getDescribe().getLabel();
value = mapFieldMapManaged.get(s).getDescribe().getName();
if(mapFieldMapManaged.get(s).getDescribe().isUpdateable()) mapLabelToFieldSV.put(key, value);
}
for(SVMXC__Service_Order__c so : lstWOManage.values()) {
newWO = new Work_Order__c();
newWO.put('SVXMX_Record_Id__c',so.get('Id'));
for(String lbl: mapLabelToFieldSV.keySet() ) {
fieldSV = mapLabelToFieldSV.get(lbl);
if(mapLabelToFieldWO.containsKey(lbl)){
fieldWO = mapLabelToFieldWO.get(lbl);
newWO.put(fieldWO ,so.get(fieldSV));
}
else continue;
}
RecordType rtSV = [Select Name From RecordType where Id = :so.RecordTypeId limit 1];
RecordType rtWO = [Select Id From RecordType where Name = :rtSV.Name and sObjectType = 'Work_Order__c' limit 1];
newWO.put('RecordTypeId',rtWO.Id); lstToInsert.add(newWO);
}
insert lstToInsert;
}
}